2017-07-07 94 views
0

用下面的渲染器...覆盖Django的渲染方法

from django.shortcuts import render 
... 
return render(request, 'template.html', {'context':context,}) 

是否有可能重写Render CLASSE的方法,让我能在某些情况下解释模板标签自己举例来说,如果我找到包括标签一定的格式,如...

{% url 'website' page.slug %} 

我可以指出它...

/theme/theme-1/page.html 

/theme/theme-2/page.html 

取决于外挂设置。

回答

1

render方法是这个的快捷方式:

template = loader.get_template(''template.html') 
context = { 
    ..., 
} 
return HttpResponse(template.render(context, request)) 

因此,不要试图更改URL标记的行为,正确的位置。

对于您给出的示例,它看起来像网站应该是一个变量,其中包含theme-1theme-2。然后,您可以将该变量传递给url标记,而不是字符串'website'

{% url website page.slug %} 

如果这是不可能的,你可以创建一个custom template tagmy_url返回根据您的设置正确的URL。

+0

其他人将负责创建模板,并会直接使用{%url%}我只希望能够在一个程序中加载多个网站,并在需要时拦截路由。这将是一个主题库,但代码必须正常运行后才能添加到实际站点。作为@alasdair指出的 –

+0

,而不是改变渲染的默认行为,你应该尝试自定义模板标签。看看这个SO帖子的例子https://stackoverflow.com/questions/6451304/django-simple-custom-template-tag-example – cutteeth

+0

你可以用你自己的标签替换Django的url标签,使用['BUILTINS' ](https://docs.djangoproject.com/en/1.11/topics/templates/#module-django.template.backends.django)选项。但我认为这不是一个好主意。你也可以看看['TemplateResponse'](https://docs.djangoproject.com/en/1.11/ref/template-response/#templateresponse-objects)而不是'render',因为它有额外的钩子。 – Alasdair