Pergunta

Is it a good idea to have/add logic inside a javascript template like so?

<time style="display: <%= time ? 'block' : 'none' %>"><%= time %></time>

How is rendering time affected by this? Is a it big difference?

Foi útil?

Solução

In general, it is wise to avoid logic in templates, although conditionally outputting a block if some value is initialized is ok.

The following, I would not have a problem with:

<% if(time) { %><time><%= time %></time><% } %>

For your situation, I would do this. In your <head> (or css):

<style>
  time:empty { display: none; }
</style>

In your template:

<time><%= time %></time>

I'm not certain about browser support for the `:empty´ pseudo-selector, but just to be safe you could also do:

$("time:empty").hide();

Outras dicas

In general, logic should not be in templates. Logic should be in models and controllers, the more of it in the models and the less in controllers, the better.

However, in the particular example you presented, the conditional is not really logic, it is more like making sure that the template does not break. So conceptually, that sort of "logic" should be present in the view.

I think Django documentation on their templates does a good job separating (and explaining) the logic that goes in the templates and the logic that does not really do in the templates. https://docs.djangoproject.com/en/dev/ref/templates/builtins/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top