Mustache / jQuery / javascript - how to execute a method on a variable mustache?

I have a simple mustache pattern setting that takes a player object and creates a list item. What is the best way to execute a javascript method for a variable in mustache? Here is a sample code:

 var playerTemplate = '<li><span class="player-position">{{ position }}</span><span class="player-name">{{ first_name }} {{ last_name }}</span></li>'; var playerRow = Mustache.to_html(playerTemplate, player); $('ul#players-list').append(playerRow); 

what i would like to do is something like:

 {{ position.toUpperCase() }} 

I would prefer not to modify the object itself, because I might want {{position}} not to be uppercase in other situations. Any tips on the cleanest smart way to do this?

Many thanks.

+6
source share
1 answer

The mustache is intentionally very simple ("patterns without logic"), so you cannot do much. One option is to add the positionUC property:

 player.positionUC = player.position.toUpperCase(); 

and then in the template:

 {{positionUC}} 

You can also add functions:

 // Note that render(text) will be HTML though... player.uc = function(text, render) { return render(text).toUpperCase() }; 

and then in the template:

 {{#uc}}{{position}}{{/uc}} 

Perhaps you can switch to Handlebars and add an assistant to the uppercase.

+6
source

Source: https://habr.com/ru/post/903536/


All Articles