如何重复“块”在django模板 [英] How to repeat a "block" in a django template
问题描述
我想在相同的django模板中使用相同的 {%block%} 两次。我想要这个块在我的基本模板中出现不止一次:
I want to use the same {% block %} twice in the same django template. I want this block to appear more than once in my base template:
# base.html
<html>
<head>
<title>{% block title %}My Cool Website{% endblock %}</title>
</head>
<body>
<h1>{% block title %}My Cool Website{% endblock %}</h1>
</body>
</html>
然后扩展它:
# blog.html
{% extends 'base.html' %}
{% block title %}My Blog{% endblock %}
# pictures.html
{% extends 'base.html' %}
{% block title %}My Pictures{% endblock %}
# cats.html
{% extends 'base.html' %}
{% block title %}My Cats{% endblock %}
我会得到一个例外,因为Django希望该块只出现一次:
I will get an exception, as Django wants the block to appear only once:
TemplateSyntaxError在/
'block'标签名称'title'出现
多次
一个快速而肮脏的解决方案将将标题复制到 title1 和 title2
A quick and dirty solution would be duplicating the block title into title1 and title2:
# blog.html
{% extends 'base.html' %}
{% block title1 %}My Blog{% endblock %}
{% block title2 %}My Blog{% endblock %}
但是这违反了 DRY 的原则。这将是非常困难的,因为我有很多继承的模板,也是因为我不想去地狱; - )
But this is a violation of the DRY principle. It would be very difficult as I have a lot of inheriting templates, and also because I don't wanna go to hell ;-)
有没有任何技巧或工作 - 周围这个问题?如何在我的模板中重复同一个块,而不需要重复所有的代码?
Is there any trick or work-around to this problem? How can I repeat the same block in my template, without duplicating all the code?
推荐答案
我认为使用上下文处理器在这种情况下是过度杀戮。您可以轻松地执行:
I think that use of the context processor is in this case an overkill. You can do easily:
#base.html
<html>
<head>
<title>{% block title %}My Cool Website{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
然后:
# blog.html
{% extends 'base.html' %}
{% block content %}
<h1>{% block title %}My Blog{% endblock %}</h1>
Lorem ipsum here...
{% endblock %}
等在...看起来像DRY兼容。
and so on... Looks like DRY-compatible.
这篇关于如何重复“块”在django模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!