【发布时间】: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.html或base.html,在我的情况下没关系)@ 987654331@ 块。我在文档中搜索了其他问题,但没有找到使用 include 语法的方法。
我做过类似的事情,但通过extends 标签。但是我不想在index.html 或base.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 代码放在一个地方(父母 <script> 标签),而不是分散在各处(就像所提供的解决方案一样)。
任何人都可以为此提供一些意见或想法吗?
谢谢!
【问题讨论】:
标签: django django-templates django-1.8