我需要添加到views.py中的扩展html {% TemplateView some_base.html%}的输出中。我不能直接使用template.html,因为扩展总是不同的,我不想给每个html文件添加{% template_name ..%}。我想做这样的事情:
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()但它不起作用。更重要的是,我想保存所有要传递给模板的变量。
发布于 2012-09-11 16:35:04
我不知道为什么你要尝试,但是你不能把{%extends ...%}放在超文本标记语言中(除非你想用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
发布于 2012-09-11 16:19:13
通过将变量template_name传递给模板,您可以在django模板中实现相同的功能。然后在模板中把这段代码放在最上面。
{% with template_name|add:".html" as template %}
{% include template %}
{% endwith %}或查看this问题以获得更多帮助。
https://stackoverflow.com/questions/12365000
复制相似问题