首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >django在视图中添加{%extends%}标签

django在视图中添加{%extends%}标签
EN

Stack Overflow用户
提问于 2012-09-11 15:42:24
回答 2查看 482关注 0票数 0

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

代码语言:javascript
复制
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()

但它不起作用。更重要的是,我想保存所有要传递给模板的变量。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-11 16:35:04

我不知道为什么你要尝试,但是你不能把{%extends ...%}放在超文本标记语言中(除非你想用django模板再次渲染它。在渲染后将该字符串添加到模板中将在模板中添加不需要的{%extends ...%}字符串。

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

代码语言:javascript
复制
>>> 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

票数 1
EN

Stack Overflow用户

发布于 2012-09-11 16:19:13

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

代码语言:javascript
复制
{% with template_name|add:".html" as template %}
{% include template %}
{% endwith %}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12365000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档