【问题标题】:Django templates, including page(s) that injects code into parent blockDjango 模板,包括将代码注入父块的页面
【发布时间】:2015-12-19 16:24:58
【问题描述】:

是否可以在另一个模板中包含一个模板(带有include django 模板标签),并通过block 标签或类似的东西将一些内容“注入”到包含(父)的页面?

假设我的项目中有以下文件结构:

App/
    (...)
    templates/
        base.html
        index.html
        _include1.html
        _include2.html
        _include3.html
        _include4.html

base.html 的代码:

<!DOCTYPE html>
<html>
<head lang="en">
    (...)
</head>
<body>
<script type="application/javascript">
    $(function () {
        {% block extra_script %}
        {% endblock %}
    });

</script>

index.html 的代码:

{% extends "base.html" %}
{% load static %}
(...)
<div class="row gutter">
    <div>
        {% include "_include1.html" with object=object%}
    </div>
    <div>
        {% include "_include2.html" with object=object %}
    </div>
    <div>
        {% include "_include3.html" with object=object %}
    </div>
    <div>
        {% include "_include4.html" with object=object %}
    </div>
</div>

而在每个_include*.html我想调用一些特定的JS函数(例如),但我想把它放在父母(index.htmlbase.html,在我的情况下没关系)@ 987654331@ 块。我在文档中搜索了其他问题,但没有找到使用 include 语法的方法。

我做过类似的事情,但通过extends 标签。但是我不想在index.htmlbase.html 中为我需要包含的每个页面定义一个块({% bloc include_* %}

所以我现在(并且有效)的解决方案是在每个包含的页面中定义一个脚本,如下所示(_include1.html):

<div>
(...)
</div>
<script>
    $(function () {
        //Code that should be placed within parents script page (this is just an example)
        var a = function (){
                    (...)
                };
        a();
    });
</script>

但是我认为有一个更好的方法来做到这一点,通过使用 django 模板引擎,而不必为需要包含的每个页面定义一个块。此外,我希望将我所有的 js 代码放在一个地方(父母 &lt;script&gt; 标签),而不是分散在各处(就像所提供的解决方案一样)。

任何人都可以为此提供一些意见或想法吗?

谢谢!

【问题讨论】:

    标签: django django-templates django-1.8


    【解决方案1】:

    尝试为此使用django-sekizai

    使用 sekizai,您可以在 &lt;/body&gt; 之前定义一个 JavaScript 块:

    {% render_block "js" %}
    

    然后,当您需要将 JavaScript 添加到该块时,您可以编写以下代码:

    {% addtoblock "js" %}
        <script type="text/javascript">
            // your JavaScript
        </script>
    {% endaddtoblock %}
    

    如果 {% addtoblock %} 块中的内容有重复,它们将只被使用一次。

    【讨论】:

    • 我会检查一下,谢谢!
    猜你喜欢
    • 2010-10-25
    • 2017-02-18
    • 2021-04-19
    • 2021-09-14
    • 2023-04-09
    • 2012-11-04
    • 1970-01-01
    • 2020-04-16
    • 2013-11-17
    相关资源
    最近更新 更多