2012-09-11 42 views
0

我需要添加到views.py中的TemplateView html {%extends some_base.html%}的輸出。 我無法直接使用html,因爲template_name會始終不同,我不想爲每個template.html文件添加{%extends ..%}。 我想要做這樣的事情:django在視圖中添加{%extends%}標記

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() 

但它不工作。甚至更多 - 我想保存所有正在傳遞給模板的變量。

+1

可能的重複:http://stackoverflow.com/questions/1331148/how-do-i-use-djangos-template-extends-variable –

+0

沒有。我想將{%extends%}字符串添加到輸出html,我不想在模板中手動添加。 – Feanor

+2

什麼?你希望實際的*原始字符串*'{%extends%}'出現在你的渲染輸出中? –

回答

1

我不知道爲什麼你想,但你不能把{%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

0

與django模板相同,您可以通過將變量template_name傳遞給模板來實現。然後在模板中將此代碼放在最頂端。

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

或查看更多幫助this問題。

+0

我不想在文件夾中更改我的模板,我想在視圖中添加額外的html。 – Feanor