在 JS 模板中添加逻辑?好主意还是坏主意?
像这样在 JavaScript 模板中添加/添加逻辑是个好主意吗?
<time style="display: <%= time ? 'block' : 'none' %>"><%= time %></time>
渲染时间如何受此影响?差别大吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,避免模板中的逻辑是明智的,尽管在初始化某个值时有条件地输出块是可以的。
以下,我不会有问题:
对于你的情况,我会这样做。在您的
(或 css)中:
在您的模板中:
我不确定浏览器是否支持“:empty”伪选择器,但为了安全起见,您也可以这样做:
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:
For your situation, I would do this. In your
<head>
(or css):In your template:
I'm not certain about browser support for the `:empty´ pseudo-selector, but just to be safe you could also do:
一般来说,逻辑不应该在模板中。逻辑应该存在于模型和控制器中,模型中的逻辑越多,控制器中的逻辑越少越好。
然而,在您提供的特定示例中,条件并不是真正的逻辑,它更像是确保模板不会破坏。因此从概念上讲,这种“逻辑”应该出现在视图中。
我认为关于模板的 Django 文档很好地分离(并解释)了模板中的逻辑和模板中不真正执行的逻辑。 https://docs.djangoproject.com/en/dev/ref/templates/内置函数/
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/