2012-09-11 2 views
0

Views.py에서 TemplateView html {% extends some_base.html %}의 출력에 추가해야합니다. 나는 html로 직접 작업 할 수 없다. 왜냐하면 template_name은 항상 다르며 {% extends .. %}를 각 template.html 파일에 추가하고 싶지 않기 때문이다. 내가 이런 걸하고 싶지 :보기에서 django add {% 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

아니요. 출력 HTML에 {% extends %} 문자열을 추가하고 싶습니다.이 템플릿을 수동으로 추가하고 싶지는 않습니다. – Feanor

+2

무엇? 렌더링 된 결과에 실제 문자열 *'{% extends %} '을 표시 하시겠습니까? –

답변

1

은 당신이하려고하는 이유를 모르겠어요하지만 당신은 장고 템플릿을 사용하여 다시 렌더링하지 않으려면 당신은 (HTML에 {%extends ...%}을 넣을 수 없습니다. 템플릿에 원치 않는 {%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

변수를 template_name을 템플릿에 전달하여 django 템플릿에서 달성 할 수있는 것과 동일합니다. 그런 다음 템플릿에서이 코드를 맨 위에 놓습니다.

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

자세한 내용은 this 질문을 참조하십시오.

+0

나는 폴더에서 내 템플릿을 변경하고 싶지 않다.보기에 추가 HTML을 추가하고 싶다. – Feanor