What is the advantage of a template without logic (like a mustache)?

Recently, I came across a mustache , which is claimed to be a template without .

>

However, there is no explanation why it is designed from a logical point of view. In another word, what is the advantage of a template without logic?

+84
templates mustache
Oct 09 '10 at 9:21
source share
13 answers

In other words, this prevents you from shooting in the foot. In the old days of JSP, it was very common that JSP files were sprinkled with Java code, which made refactoring much more difficult since you had code scattered around.

If you prevent logic in design patterns (such as a mustache), you will have to put the logic in a different place so that your patterns are uncluttered.

Another advantage is that you have to think in terms of separation of problems: your controller or logic code will have to massage the data before sending the data to the user interface. If you later switch your template to another one (let's say you start using a different template engine), the transition will be simple because you only had to implement the details of the user interface (since there is no logic on the template, remember).

+92
Feb 09 2018-11-11T00:
source share

I have the feeling that I am almost alone, in my opinion, but I am firmly in the opposite camp. I do not think that the possible confusion of business logic in your templates is a sufficient reason not to use the full power of your programming language.

A common argument for templates without logic is that if you have full access to your programming language, you can mix logic that has no place in the template. I find it akin to reasoning that you should use a spoon to cut meat, because you can cut yourself if you use a knife. This is very true, and yet you will be much more productive if you use the latter, albeit with caution.

For example, consider the following template fragment using mustache :

{{name}}: <ul> {{#items}} <li>{{.}}</li> {{/items}} </ul> 

I can understand this, but I find the following (using underscore ) to be much simpler and more direct:

 <%- name %>: <ul> <% _.each(items, function(i){ %> <li><%- i %></li> <% }); %> </ul> 

As I said, I understand that logical patterns have advantages (for example, they can be used with several programming languages ​​without changes). I think these other benefits are very important. I just don’t think that their logical nature is one of them.

+61
May 03 '11 at 03:27
source share

Mustaches have no less logic?

Isn't it like this:

 {{#x}} foo {{/x}} {{^x}} bar {{/x}} 

Pretty similar to that?

 if x "foo" else "bar" end 

And isn't that like (reading: almost defining) presentation logic?

+23
21 Oct '12 at 1:30
source share

A template without logic is a template that contains holes to fill, not how to fill them. The logic is placed elsewhere and displayed directly in the template. This separation of problems is ideal, because then the template can be easily built with different logic or even with a different programming language.

From the mustache manual:

We call this “no logic” because there are no if, else else, or loop statements. Instead, there are only tags. Some tags are replaced with a value, nothing but the other series of values. This document explains the different types of mustache tags.

+13
Oct 17 '10 at 21:32
source share

This makes your templates cleaner, and it forces you to keep the logic in the place where it can be checked with the module.

+11
Oct 10 '10 at 3:29
source share

The flip side of the coin is that in a desperate attempt to get the business logic out of the presentation, you end up putting a lot of presentation logic into the model. A common example might be that you want to put the "odd" and "even" classes into variable rows in a table, which can be done using the simple modulo operator in the view template. But if your viewing template does not allow you to do this, then in the model data you need to not only save which line is odd, but also accurate, but depending on how limited your template engine is, you may even need to pollute your model with The names of the actual CSS classes. Views should be separated from full stop models. But models must also be View agnostic, and that many of these "non-logical" template engines make you forget. Logic goes in both places, but you have to be reasonable about what logic really does in order to correctly decide where it goes. Is this a problem for presentation or concern for business / data? In order to have a 100% pristine appearance, the pollution simply falls into another less noticeable, but no less suitable place.

There is a growing backward movement in a different direction , and, hopefully, something will be somewhere in a more reasonable environment.

+9
Nov 25 '12 at 18:19
source share

This conversation seems to be when the monks of the Middle Ages discuss how many angels can fit on the end of a pin. In other words, he begins to feel religious, unhelpful, and wrongly focused.

A mini rant appears (feel free to ignore):

If you do not want to continue reading. My short answer to the above topic: I do not agree with templates without logic. I think of it as a programming form of extremism. :-) :-)

Now my disclosure continues in full swing :: -)

I think that when you take a lot of ideas to the extreme, the result becomes ridiculous. And sometimes (i.e. this topic) the problem is that we take the “wrong” idea to the extreme.

Removing all logic from a view is a “ridiculous” and wrong idea.

Come back for a moment.

The question we need to ask ourselves is why do we need to remove the logic? The concept is obviously a separation of concerns . Keep view processing as separate from business logic as possible. Why do this? This allows us to change the view (for different platforms: mobile, browser, desktop, etc.), and it allows us to more easily exchange the control flow, page sequence, validation changes, model changes, access to security, etc. Also, when the logic is removed from the views (especially web views), it makes the views more readable and therefore more convenient for maintenance. I understand this and agree with that.

However, the focus should be on the separation of issues. Not 100% without logic. The logic in the views should relate to how to visualize the “model”. As far as I know, the logic in the views is absolutely beautiful. You may have a view logic that is not business logic.

Yes, back on the day when we wrote JSP, PHP, or ASP pages with little separation of code logic and viewing logic with or without it, serving these web applications was an absolute nightmare. Believe me, I know, I created and then supported some of these monsters. It was at this stage of the service that I really understood (visually) the error of my and my colleagues. :-) :-)

So, the edict from above (industry experts) has become, you have to structure your web applications using something like a controller in the foreground (which is sent to handlers or actions [select your web framework]), and your views should not contain code . Representations were supposed to be dumb patterns.

Thus, in general, I agree with the aforementioned feeling, and not on the specifics of the edict clauses, but rather on the motivation of the edict - this is the desire to distinguish between problems between the view and business logic.

In one project in which I participated, we tried to follow the idea without logic with an absurd extreme. We had a home template engine that would allow us to display model objects in html. It was a simple token based system. This was terrible for one simple reason. Sometimes in a view, we had to decide whether I should display this small piece of HTML .. or not .. The decision is usually based on some value in the model. When you have absolutely no logic in the presentation, how do you do it? Well, you can’t. I had some serious arguments in favor of our architect. The external HTML people who write our views were completely rooted when they encountered this, and were very stressed because they could not achieve their simple goals. Therefore, I introduced the concept of a simple IF statement in our template. I cannot describe to you the relief and calm that ensued. The problem was solved using the simple IF-Statement concept in our templates! Suddenly our template engine became good.

So, how did we get into this stupid stressful situation? We focused on the wrong goal. We followed the rule, you should not have logic in your views. This was wrong. I think the “rule of thumb” should be, minimize the amount of logic in your views. Because, if you do not, you may inadvertently allow business logic to penetrate the view - which violates the separation of concerns.

I understand that when you state that “you should not have logic in your views”, it becomes easy to find out when you are a “good” programmer. (If this is your measure of goodness). Now try to implement a web application of even medium complexity using the above rule. This is not so easy to do.

For me, the rule of logic in representations is not so clear and frank that I want it to be.

When I see a lot of logic in the views, I smell the code and try to remove most of the logic from the views - I try to ensure the life of the business logic elsewhere - I try to separate the problems. But when I start chatting with people who say that we need to remove all logic from the view, well, for me, this is simply amazing fanaticism, because I know that you can be in situations like those described above.

I ended up with my flatulence. :-)

Greetings

David

+6
Feb 03 '13 at 16:50
source share

The best argument I came up with for faceless templates is the same as on the client and on the server. However, you really do not need a logical one, just one that has its own "language". I agree with people who complain that a mustache is pointlessly limiting. Thank you, but I'm a big boy, and I can save my templates without your help.

Another option is to simply find a template syntax that uses a language that is supported on both the client and the server, namely javascript on the server, either using node.js, or you can use the js interpreter and json via something like therubyracer.

Then you can use something like haml.js, which is much cleaner than any of the above examples and works just fine.

+5
Jan 22 2018-12-22T00:
source share

In one sentence: Logic-less means that the template engine itself is less complex and therefore has a smaller size and there are fewer ways for it to behave unexpectedly.

+4
May 10 '12 at 13:16
source share

Despite the fact that the question is old and answers, I would like to add my 2 ¢ (which may seem pompous, but it’s not, its limitations and when they become unacceptable).

The purpose of the template is to give out something, and not to execute business logic. Now there is a thin line between the fact that you cannot do what you need to do in the template and have a “business logic” in them. Despite the fact that I really had a positive attitude towards Mustache and tried to use it, I was not able to do what I needed in fairly simple cases.

"massing" the data (using words in the accepted answer) can be a real problem - even simple paths are not supported (something regarding Handlebars.js). If I have view data and I need to set it up every time I want to do something, because my template engine is too limited, then this does not help in the end. And he defeats the piece of platform independence that the mustache claims for itself; I have to duplicate the logic of massage everywhere.

However, after some disappointment and after we tried other template engines, we created our own (... one more ...) that uses the syntax created by .NET Razor templates. It is analyzed and compiled on the server and generates a simple stand-alone JS function (actually as a RequireJS module), which can be called to "execute" the template, returning a string as the result. The sample provided by brad will look like this when we use our engine (which I personally find much better in a readable comparison compared to Mustache and Underscore):

 @name: <ul> @for (items) { <li>@.</li> } </ul> 

Another limitation without logic struck us when you called a particle from a Mustache. Although partial files are supported by Mustache, there is no way to configure the data that will be transferred first. So instead of creating a modular template and reusing small blocks, I end up making templates with repeating code in them.

We decided that by implementing a query language inspired by XPath, which we called JPath. Basically, instead of using / to move to children, we use dots, and not only string, numeric and Boolean literals are supported, but also objects and arrays (like JSON). The language is free from side effects (which is mandatory for templates), but allows you to "massage" the data as necessary, creating new literals.

Suppose we want to display a “data grid” table with cusomizable headers and row action links, and then dynamically add rows using jQuery. Therefore, strings should be partial if I do not want to duplicate the code. And where the problem arises, if some additional information, for example, which columns should be visualized, is part of the presentation model and is the same for these actions in each row. Here is some actual working code using our template and query mechanism:

Table Template:

 <table> <thead> <tr> @for (columns) { <th>@title</th> } @if (actions) { <th>Actions</th> } </tr> </thead> <tbody> @for (rows) { @partial Row({ row: ., actions: $.actions, columns: $.columns }) } </tbody> </table> 

String Pattern:

 <tr id="@(row.id)"> @for (var $col in columns) { <td>@row.*[name()=$col.property]</td> } @if (actions) { <td> @for (actions) { <button class="btn @(id)" value="@(id)">@(name)...</button> } </td> } </tr> 

Call from JS code:

 var html = table({ columns: [ { title: "Username", property: "username" }, { title: "E-Mail", property: "email" } ], actions: [ { id: "delete", name: "Delete" } ], rows: GetAjaxRows() }) 

It has no business logic, but it is reusable and customizable, and it is also a side effect.

+3
Oct 28 '11 at 17:44
source share

Here are three ways to render a list, with a character number. All but the first and shortest have logic patterns without patterns.

CoffeeScript (with jet coffee maker DSL) - 37 characters

 "#{name}" ul items.map (i) -> li i 

Knockout - 100 characters

 <span data-bind="value: name"/> <ul data-bind="foreach: items"> <li data-bind="value: i"/> </ul> 

Pens / Mustache - 66 characters

 {{name}}: <ul> {{#items}} <li>{{.}}</li> {{/items}} </ul> 

Underscore - 87 characters

 <%- name %>: <ul> <% _.each(items, function(i){ %> <li><%- i %></li> <% }); %> </ul> 

The promise of patterns without logic was, I suppose, that people with wider skills could manage patterns without logic without shooting themselves in the foot. However, what you see in the above examples is that when you add a minimally logical language to the line-based markup, the result is more complex, no less. Plus, you look like you're using old school PHP.

It’s clear that I don’t mind saving “business logic” (advanced computation) from templates. But I think that by giving them a pseudo-language for display logic instead of first-class language, the price is paid. Not just typing anymore, but a disgusting combination of context switching, someone needs to read it.

In conclusion, I do not see the logic of templates without logic, so I would say that their advantage is zero for me, but I respect that many in the community see it differently :)

+1
Feb 15 '14 at 5:29
source share

I agree with Brad: the underscore style is easier to understand. But I have to admit that syntactic sugar cannot please everyone. If _.each somewhat confusing, you can use the traditional for loop.

  <% for(var i = 0; i < items.length; i++) { %> <%= items[i] %> <% } %> 

It is always good if you can refuse standard constructions, such as for or if . Just use <% if() %> or <% for() %> , and Mustache use a little neologism for if-then-else (and confusing if you haven't read the documentation):

 {{#x}} foo {{/x}} {{^x}} bar {{/x}} 

The template engine works great when you can easily insert nested templates ( underscore style):

 <script id="items-tmpl" type="text/template"> <ul> <% for(var i = 0; i < obj.items.length; i++) { %> <%= innerTmpl(obj.items[i]) %> <% } %> </ul> </script> <script id="item-tmpl" type="text/template"> <li> <%= name %> </li> </script> var tmplFn = function(outerTmpl, innerTmpl) { return function(obj) { return outerTmpl({obj: obj, innerTmpl: innerTmpl}); }; }; var tmpl = tmplFn($('#items-tmpl').html(), $('#item-tmpl').html()); var context = { items: [{name:'A',{name:'B'}}] }; tmpl(context); 

Basically you pass your internal tmpl as a property of your context. And name it accordingly. Sweet:)

By the way, if the only mechanism you are interested in is the template engine, use an offline template implementation. It is only 900 characters when mining (4 long lines):

https://gist.github.com/marlun78/2701678

+1
Feb 15 '14 at 11:02
source share

The main advantages of using templates without logic are:

  • Strictly provides separation of the model view , see this document for details (recommended)
  • It is very easy to understand and use , because programming logic (and knowledge!) Is not needed, and the syntax is minimal
  • (specific Mustache) highly portable and language independent, can be used unchanged in almost all programming environments
0
Sep 15 '17 at 8:38 on
source share



All Articles