【问题标题】:Can I override blocks in the parent template from Django templatetags?我可以从 Django 模板标签覆盖父模板中的块吗?
【发布时间】:2011-10-18 08:17:37
【问题描述】:

我正在为 Django 编写一个模板标签包,以便在 Django 应用程序中轻松包含 RGraph 图。

我在使用包含 javascript 的模板时遇到了一些问题,我在我的基本 html 文件中定义了一个块,我希望模板标签的模板提供该块。

这是我的顶级模板

{% load django_rgraph %}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>Test Charts</title>
    {% block js %}
    {% block js.custom %}{% endblock %}
    {% endblock %}
</head>

<body>

{% rgraph piechart %}

</body>
</html>

这是我的新标签的模板

{% extends "django_rgraph/rgraph_base.html" %}

{% block rgraph_chart %}
<script>
window.onload = function() {
    var {{ chart.name }} = new RGraph.Pie('{{ chart.name }}', [{% for value in chart.values %}{{ value }}{% if not forloop.last %},{% endif %}{% endfor %}]);
    {% for option, value in chart.options.items %}
    {{ chart.name }}.Set('{{ option }}', {{ value }});
    {% endfor %}

    {% if chart.animate %}
    RGraph.Effects.Pie.RoundRobin({{ chart.name }});
    {% else %}
    {{ chart.name }}.Draw();    
    {% endif %}
}
</script>
{% endblock %}

为了完整起见,rgraph_base.html 看起来像这样

{% block js.custom %}
{% for js in chart.js %}
<script src="RGraph/js/{{ js }}"></script>
{% endfor %}
{% endblock %}

{% block rgraph_chart %}Insert Chart Here{% endblock %}

我希望这会创建一个 html 页面,其中 javascript 包含在标题中,但它出现在正文中,就像这样

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>Test Charts</title>
</head>

<body>

<!-- I was expecting these script tags to be below the title tag -->
<script src="RGraph/js/RGraph.common.core.js"></script>
<script src="RGraph/js/RGraph.common.tooltips.js"></script>
<script src="RGraph/js/RGraph.common.effects.js"></script>
<script src="RGraph/js/RGraph.pie.js"></script>

<script>
window.onload = function() {
    var pie1 = new RGraph.Pie('pie1', [10,24,15,82]);
    pie1.Set('chart.gutter.left', 30);
    pie1.Draw();
}
</script>
</body>
</html>

有了这个设置,新标签中的模板覆盖了顶层模板中定义的块,我应该能够让脚本出现在顶部标签中吗?

【问题讨论】:

  • 脚本出现在正文中,因为 rgraph 标签被插入到正文中。没有?
  • @akonsu,这就是我要问的,在标签的模板中有一个与父级同名的块,我期待与普通模板相同的行为,即块子级将覆盖父级中的块。
  • 显然 django 模板的行为不是这样的。此外,您期望的行为是否正确值得怀疑。毕竟,您只需将标签插入正文即可。您不是从具有要填充的块的顶级模板派生的。

标签: django django-templates


【解决方案1】:

Akonsu 是对的,你对 django 模板标签有误解,它们不能覆盖其他块。

【讨论】:

    猜你喜欢
    • 2013-05-22
    • 1970-01-01
    • 2018-10-21
    • 2012-10-24
    • 2018-01-01
    • 2018-02-22
    • 2011-02-09
    • 1970-01-01
    • 2011-07-21
    相关资源
    最近更新 更多