Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore tags with MustacheJS

I am currently facing a problem with MustacheJS templates by trying to build widgets modules.

In facts, I use my html templates twice :

  • Server parse the html template and render it with server datas
  • Client download page builded by server (so already rendered by mustache on server side) and I want to apply a second render of Mustache in the browser, after ajax requests.

But the problem is that as vars are empty on server side, template html is not rendered on client side...

<!-- Rendered on server side -->
<div class="content noise">
    <h4>{{widget.title}}</h4>
    <p>Issues from {{widget.github.author}}/{{widget.github.repo}}</p>
    <div class="issues"></div>
</div>

<!-- I want to render this only on client side -->
<script type="text/template" id="issueTemplate">
{{#links}}
    <a href="{{url}}" {{#selected}}class="Selected"{{/selected}}>{{{name}}}</a>
{{/links}}
</script>

Here issueTemplate is empty, as {{links}} is empty on server side.

On client side, I try something like this, and replacing "{{" tag by "[[", but it doesn't have effects :

self.mu = _.clone(Mustache) ;
self.mu.tags = ['[[', ']]'] ;

So do you have an idea about how to ignore tags from rendering, 'script' for example?

like image 334
G33k Labs Avatar asked Dec 07 '22 12:12

G33k Labs


1 Answers

In Mustache you can change tag delimiters on the fly by using a {{= ... =}} tag; you can use this to create literal sections by picking delimiters that don't exist in the literal. Thus you could do something like

<!-- Rendered on server side -->
<div class="content noise">
  <h4>{{widget.title}}</h4>
  ...
<!-- I want to render this only on client side -->

{{={{{ }}}=}}
<!-- Now only triple braces will be interpreted as tags on the server side -->
<!-- Double braces will be passed through literally -->

<script type="text/template" id="issueTemplate">
{{#links}}
...
{{/links}}
</script>

{{{={{ }}=}}}
<!-- Now double braces delimit tags again if you need to do more server-side rendering-->
like image 113
ebohlman Avatar answered Dec 11 '22 08:12

ebohlman