Django包含html而不解析模板标签

时间:2015-05-14 00:16:34

标签: javascript django templates

我正在创建一个基于Django的Web应用程序,它是服务器端呈现的。但是现在有一些页面我想使用来自Feed的javascript重新渲染。

我更喜欢使用DRY方法并重新使用我现有的Django模板,将它们包含在标签内的页面上。

然后我可以使用我选择的模板库(有许多支持Django模板)

然而,我坚持最简单的事情,包括模板而不解析!以下是我尝试过的无效方法

预期输出

<ul>
    <li>John Doe</a></li>
    <li>Sally Taylor</a></li>
    <li>David Smith</a></li>
</ul>
<script type="text/template">
    <ul>
    {% for person in people %}
        <li>{{ person.name }}</a></li>
    {% endfor %}
    </ul>
</script>

方法1 - 有效,但我必须重复两次相同的HTML

的index.html

{% include "includes/list.html" %}
<script type="text/template">
    {% include "includes/list.html" with script=1 %}
</script>

list.html

{% if script = 1 %}
{% verbatim %}
    <ul>
        {% for person in people %}
            <li>{{ person.name }}</a></li>
        {% endfor %}
    </ul>
{% endverbatim %}
{% else %}
<ul>
    {% for person in people %}
        <li>{{ person.name }}</a></li>
    {% endfor %}
</ul>
{% endif %}

方法2 - 到达循环后不输出

的index.html

{% include "includes/list.html" %}
<script type="text/template">
    {% include_raw "includes/list.html" %}
</script>

tags.py

from django import template
from django.template import loader, Context

register = template.Library()

@register.simple_tag
def include_raw(templatename):
    return loader.get_template(templatename).render(Context())

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

所以我用这个解决方案解决了它: https://gist.github.com/HenrikJoreteg/742160

使其运作的代码是:

的index.html

{% load pages_tags %}
{% include "includes/list.html" %}
<script type="text/template">
    {% raw_include "includes/list.html" %}
</script>

list.html

<ul>
    {% for person in people %}
        <li>{{ person.name }}</a></li>
    {% endfor %}
</ul>

pages_tags.py

from django import template, conf
register = template.Library()

@register.simple_tag
def raw_include(path):
    import os.path

    for template_dir in conf.settings.TEMPLATE_DIRS:
        filepath = '%s/%s' % (template_dir, path)
        if os.path.isfile(filepath):
            break

    fp = open(filepath, 'r')
    output = fp.read()
    fp.close()
    return output

这是一个示例项目,显示它们一起工作,包括使用JavaScript呈现客户端模板:

https://github.com/kmturley/django-client-templates

我还制作了这个jsperf来测试不同的jinja样式模板库的性能:

https://jsperf.com/jinja-client-side-libraries/5