如何重复一个“块"在 Django 模板中 [英] How to repeat a "block" in a django template

查看:19
本文介绍了如何重复一个“块"在 Django 模板中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在同一个 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 at/

出现名为title"的block"标签不止一次

一个快速而肮脏的解决方案是将块 title 复制到 title1title2 中:

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 easily do this:

#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆