Django:DRY 与逻辑分离有根本冲突吗?
这类似于这个问题:如何在 a 中使用方法参数Django 模板?
我理解(并且同意并欣赏)业务逻辑与表示逻辑分离的基本 django 哲学。
然而,有时这似乎让 DRY 变得更加困难,而 DRY 是一种更严重的实践,不是吗?
假设我有一个用于面包屑导航的模板。我为每个导航层一遍又一遍地重复使用(通过包含)此模板。又好又干。但我希望模板知道它代表的是导航的哪个迭代。
我发誓我记得一个方法来完成这个 - 类似 {% include 'llamas'html' | 2 %} 但我可能是错的。
如果是,我怎样才能在不违反逻辑分离原则的情况下保持这个模板(和导航)干燥?
This is similar to this question: How to use method parameters in a Django template?
I understand (and agree with and appreciate) the basic django philosophy of separation of business logic from presentation logic.
However, at times it seems to make DRYness more difficult, and DRY is a practice of even greater gravity, no?
Let's say I have a template that I use for breadcrumb navigation. I re-use (by including) this template over and over for each navigation layer. Nice and dry. Yet I want the template to know which iteration of the nav it is representing.
I swear I remember a method to accomplish this - something like {% include 'llamas'html' | 2 %} but I may be wrong.
If I am, how can I keep this template (and the navigation) DRY without violating the principle of separation of logic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还可以从包含或内联面包屑代码的通用模板进行扩展,而不是包含。
例如 sometemplate.html:
另外,如果您不想在某些页面上有面包屑,则可以在“base_with_breadcrumbs.html”内将面包屑包装到 {% if with_crumbs %}...{% endif %} 语句中。
在基本模板内,您可以定义可以在派生模板中填充的块。
另外,看看 jinja2,它与 django 类似,但有许多不错的功能。我已经在 jinja 中为我的项目重写了 50 多个模板,并且从未回头。
Instead of including, you might also extend from a common template that includes or inlines the code for breadcrumbs.
e.g. sometemplate.html:
Also, if you don't want to have breadcrumbs on some pages, inside the "base_with_breadcrumbs.html" you can wrap the crumbs into an {% if with_crumbs %}...{% endif %} statement.
Inside the base template you can define blocks that may be populated in the derived templates.
Also, take a look at jinja2, it is similar to django, but has many nice features. I've rewritten 50-some templates in jinja for my project and never looked back.
我的建议是切换到 Jinja2。
include
标签基本上是相同的,但是您还拥有macro
标签,它为您提供了一个可调用块,可以轻松地与变量一起重用。include 标记的一些变化:
使用宏,您可以执行如下操作:
可以这样调用:
假设带有宏的文件是
forms.html
。您还可以将宏放在同一个文件中,这样就不必导入。My advice would be to switch to Jinja2. The
include
tag is mostly the same, but you also have themacro
tag which gives you a callable block which can be easily reused with variables.Some variation on the include tag:
With macros you can do stuff like this:
Which can be called like this:
Assuming that the file with the macro is
forms.html
. You can also put the macro in the same file so you won't have to import.