<div class="document">
<p>Here are two methods to output an HTML template as it is using Django's TemplateView class, but replacing strings in the output result at once.</p>
<p>We will handle this in urls.py without using middleware.</p>
<div class="section" id="as-view">
<h3>Method 1: Decorate the result of as_view</h3>
<p>urls.py</p>
<pre class="literal-block">url(r'^hoge-page/$',
TemplateView.as_view(
template_name="hoge-page"),
name='hoge-page'),
</pre>
<p>▲ Change this to:</p>
<pre class="literal-block">url(r'^hoge-page/$',
content_replace_decorator(TemplateView.as_view(
template_name="hoge-page")),
name='hoge-page'),
</pre>
<p>▲ We will use a decorator to perform string replacement in the output result in this form.</p>
<pre class="literal-block">def content_replace_decorator(func):
@functools.wraps(func)
def wrapper(view, *args, **kwargs):
result = func(view, *args, **kwargs)
def callback(response):
response.content = response.content.replace(
FROM_WORD.encode('utf-8'),
TO_WORD.encode('utf-8'))
if isinstance(result, HttpResponse):
result.add_post_render_callback(callback)
return result
return wrapper
</pre>
</div>
<div class="section" id="templateview">
<h3>Method 2: Create a class that inherits from TemplateView</h3>
<pre class="literal-block">url(r'^hoge-page/$',
TemplateView.as_view(
template_name="hoge-page"),
name='hoge-page'),
</pre>
<p>▲ Change this to:</p>
<pre class="literal-block">url(r'^hoge-page/$',
ContentReplaceTemplateView.as_view(
template_name="hoge-page"),
name='hoge-page'),
</pre>
<p>▲ Consider a class that performs string replacement in the output result.</p>
<pre class="literal-block">class ContentReplaceTemplateView(TemplateView):
@staticmethod
def callback(response):
response.content = response.content.replace(
FROM_WORD.encode('utf-8'),
TO_WORD.encode('utf-8'))
def get(self, request, *args, **kwargs):
result = super(ContentReplaceTemplateView, self).get(
request, *args, **kwargs)
result.add_post_render_callback(self.callback)
return result
</pre>
<p>In any case, the key point is to insert the conversion method into the add_post_render_callback of the HttpResponse instance.</p>
<p>If you try to directly manipulate the content of the HttpResponse instance without doing this, an exception will be raised.</p>
</div>
</div>
Comments