【问题标题】:django add {%extends%} tag in the viewdjango 在视图中添加 {%extends%} 标签
【发布时间】:2012-09-04 02:31:48
【问题描述】:

我需要在views.py 中添加到TemplateView html {%extends some_base.html%} 的输出。 我不能直接使用 html,因为 template_name 总是不同的,我不想将 {%extends..%} 添加到每个 template.html 文件中。 我想做这样的事情:

class PageView(TemplateView):

def get_context_data(self, **kwargs):
    object = PageModel.objects.get(view_base__slug=kwargs.get('slug'))
    self.template_name = object.template_name
    self.base='base.html'
    from django.template.loader import render_to_string
    #just example, it's not working
    rendered = render_to_string(self.template_name) 
    rendered= '{% extends' + self.base + '%} '+ rendered
    ###
    return locals()

但它不起作用。甚至更多 - 我想保存所有正在传递给模板的变量。

【问题讨论】:

  • 没有。我想将 {% extends %} 字符串添加到输出 html,我不想在模板中手动添加。
  • 什么?您希望实际的 原始字符串 {% extends %} 出现在您的渲染输出中吗?
  • 是的,这就是我想要的。我希望它由 django 处理并用于扩展 base.html
  • 但这与我所说的相反! 要么 你希望原始字符串出现在渲染输出中,要么 你希望它作为模板的一部分由 Django 处理。哪个?

标签: django django-templates django-views


【解决方案1】:

通过将变量template_name 传递给模板,您可以在 django 模板中实现相同的目的。然后在模板中把这段代码放在最上面。

{% with template_name|add:".html" as template %}
{% include template %}
{% endwith %}

或查看this 问题以获得更多帮助。

【讨论】:

  • 我不想更改文件夹中的模板,我想在视图中添加额外的 html。
【解决方案2】:

我不确定你为什么要尝试但你不能将{%extends ...%} 放入 HTML 中(除非你想使用 django 模板再次渲染它。在渲染后将该字符串添加到模板中会在模板中添加不需要的 {%extends ...%} 字符串.

但是,如果您愿意,您可以动态创建模板并渲染它。新模板可以扩展现有模板。 例如:

>>> from django.template import Template, Context
>>> #creates a template from string, "base.html" can be self.base in your case
>>> t = Template('{%extends "' + "base.html" + '"%} ...') 
>>> c = Context({'your_var1': 'var1_value'})            #get context for template
>>> t.render(c)                                         #render the created template 
u'\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n
 <html xmlns="http://www.w3.org/1999/xhtml">
....

更多参考:Template Compiling a string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    相关资源
    最近更新 更多