How to reuse the same code in several Display Templates?

57 views Asked by At

I have 2 Display Templates that have the same code on a few lines.

Is there is a way to move a common code to another file and reference that file in both templates?

For example:

Display Template #1 and # 2 have the following common code:

IFormatProvider formatProvider = System.Globalization.CultureInfo.CurrentCulture;
string formattedCurrency = null;

if (formatProvider.ToString().Equals("en-US"))
{
    formattedCurrency = (@Model < 0 ? @Model.ToString("C", formatProvider) : (@Model).ToString("C", formatProvider));
}
else
{
    formattedCurrency = (@Model < 0 ? "- " + @Math.Abs(@Model).ToString("C", formatProvider) : (@Model).ToString("C", formatProvider));
}

How can I move it to a separate file and reference that from both templates?

1

There are 1 answers

0
David Espino On

So my first option was to have the formattedCurrency prop as a common function:

public class LocalizedViewModel {
   private IFormatProvider formatProvider;
   public float Currency { get; set; }
   public string FormattedCurrency () {
     if (formatProvider.ToString().Equals("en-US"))
     {
         return  (this.Currency < 0 ? this.Currency.ToString("C", formatProvider) : (this.Currency).ToString("C", formatProvider));
     }
     else
     {
         return (this.Currency < 0 ? "- " + Math.Abs(this.Currency).ToString("C", formatProvider) : (this.Currency).ToString("C", formatProvider));
     }
   }
  public LocalizedViewModel () {
    formatProvider = System.Globalization.CultureInfo.CurrentCulture;
  }
}

And then inherit both ViewModels from this base model

public class MyModel1: LocalizedViewModel {
   public MyModel1() : base() {
   }
}

public class MyModel2: LocalizedViewModel {
   public MyModel2() : base() {
   }
}

Then every time you create an object you have access to this prop:

var myModel = new Model1();
var myModel2 = new Model2();
myModel.Currency = 100;
myModel2.Currency = 200;

Now both viewmodels will have the formattedCurrency to display on any view, without the need on any extra view logic. Hope this helps and could be a viable option to you.

myModel.FormattedCurrency();
myModel2.FormattedCurrency();

And render that property on any template. Again this is an alternative solution to achieve the same results. But with a different approach.

Regards