Include template as verbatim - django

I have a template which I'm inserting with include tag:
{% include 'template.html' %}
Also in another place I want its contents to be displayed as raw. How can I achieve this?

You can try something like:
page1.html
{%with flag="norender" %}
{% include "template.html" %}
{%endwith%}
template.html
{%if flag == "norender" %}
{%verbatim%}
{%endif%}
{#your html #}
{%if flag == "norender" %}
{%endverbatim%}
{%endif%}

I ended up creating a template tag to do this:
from django import template
from django.template.loader import get_template
from django.utils.html import escape
register = template.Library()
#register.simple_tag()
def verbatim_include(name):
"""
Example: {% verbatim_include "weblog/post.html" %}
"""
template = get_template(name)
return escape(template.render())
I've no idea if it's the best or most efficient method, but it seems to work OK for me (Django 1.11).
In my main template I'll include another like this:
<pre><code>{% verbatim_include 'my_template.html' %}</code></pre>
And if my_template.html is like this:
<b>This is my template</b>
Then in the browser I'll see:
<b>This is my template</b>
And not:
This is my template

Tested on Django 1.11:
from django import template
from django.template.loader import get_template
from django.utils.safestring import mark_safe
register = template.Library()
#register.simple_tag
def verbatim_include(name):
"""
Example: {% verbatim_include "weblog/post.html" %}
"""
template = get_template(name)
source = template.template.source
return mark_safe(source)

Related

Django template is not displaying

Assuming my model contains data, I have myapp/views.py:
from django.template import RequestContext
from django.shortcuts import render
from .models import History
import datetime
def live_view(request):
context = RequestContext(request)
plays_list = History.objects.filter(date=datetime.date(2016,04,22))
context_list = {'plays':plays_list}
return render(request,'live.html',context_list)
myapp/templates/live.html:
{% extends 'base.html' %}
{% block content %}
{% for key, value in context_list.items %}
{{ value }}
{% endfor %}
{% endblock %}
myapp/urls.py:
from myapp.views import live_view
urlpatterns = [url(r'^live/$', live_view, name="live"),]
The output is a page that renders only the base.html template, with no content in the body. What's wrong with my view function or template rendering? Should I be inheriting from TemplateView?
You don't pass anything called context_list to the template. What you pass is the contents of that dict, which in this case is just plays.

Unresolved tag in PyCharm

I have this issue of pycharm showing me unresolved tag after i successfully loaded the file containing the custom tag. Please someone help!!
this is the content of my carton-tags.py file containing custom template tags
from django import template
from carton.cart import Cart
from carton.settings import CART_TEMPLATE_TAG_NAME
register = template.Library()
#register.filter
def get_cart(context, session_key=None, cart_class=Cart):
"""
Make the cart object available in template.
Sample usage::
{% load carton_tags %}
{% get_cart as cart %}
{% for product in cart.products %}
{{ product }}
{% endfor %}
"""
request = context['request']
return cart_class(request.session, session_key=session_key)
register.assignment_tag(takes_context=True, name=CART_TEMPLATE_TAG_NAME)(get_cart)
You are using get_cart filter as a template tag in you template. This is why pycharm is showing errors.
#register.filter
def get_cart(context, session_key=None, cart_class=Cart):
You should remove register.filter decorator if you are not using it as a filter.

django render an object as html in a template

I am trying to render an object in a template like what we can do with forms {{ form }} but the output is turned into text and not html code. How to really include html code?
my_object = MyObject()
{{ my_object }}
The class:
from django.template import Context, Template
from django.utils.safestring import mark_safe
class MyObject(object):
def __str__(self):
return self.render()
def render(self):
t = Template('<p>This is your <span>{{ message }}</span>.</p>')
c = Context({'message': 'Your message'})
html = t.render(c)
return mark_safe(html)
You should be implementing __unicode__ instead of __str__. The templating module stringifies context variables as unicode.
You can also use
{% autoescape off %}
{{ info }}
{% endautoescape off %}
But you must be care to avoid xss vulnerabilities.
If the attempt is to get html on to the page then you should be using {{myobject|safe}}. That should render the HTML code instead of text

how to get template working in django?

I was on the 3rd tutorial of this https://docs.djangoproject.com/en/1.5/intro/tutorial03/ site. I got stuck where we load template for our views under the section Write views that actually do something.
The first code is working fine ( as there is no template loading):
from django.http import HttpResponse
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
output = ', '.join([p.question for p in latest_poll_list])
return HttpResponse(output)
But when I laod the template with code below it shows same result as above( that is
with no template)
from django.http import HttpResponse
from django.template import Context, loader
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = Context({
'latest_poll_list': latest_poll_list,
})
return HttpResponse(template.render(context))
The template use is:
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li>{{ poll.question }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
The template is in polls/template/polls/index.html where polls is my app( as used in tutorial)
PS:I have followed everything as it is till this point from tutorial.
As you can see in the Django documentation, django.template.loaders.app_directories.Loader looks for template files in a directory named templates inside the app directory.
You said that your template is in "polls/template/polls/index.html", but it should be in "polls/templates/polls/index.html" (notice the added s to templates).

inherited python vars in nested tornado templates

I am trying to nest tornado templates using {% include %}:
<html>
{% for headline in HL['headlines'] %}
{% include 'hl_1.html' %}
{% end %}
</ul>
</body>
</html>
The template above works, and the sub-template above works. What I cannot figure out how to do is pass in the name of the sub-template (e.g.replacing 'hl_1.html' with a string parameter in the parent template's namespace). AFter reviewing the template.py source code it seems that {% include accepts a string and nothing else. But it would be fantastic if one could dynamically specify sub-templates.
Has anyone tried this and succeeded?
thanks
The way this is achieved usually is by using UI modules.
This is how I would structure your app.
First main.py:
import tornado.ioloop
import tornado.web
import views
class MainHandler(tornado.web.RequestHandler):
def get(self):
HL = {
'headlines': ['head1', 'head2', 'head3'],
}
self.render('tmpl.html', HL=HL)
if __name__ == "__main__":
application = tornado.web.Application([
(r"/", MainHandler),
], ui_modules=views)
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Then your template tmpl.html:
<html>
{% for headline in HL['headlines'] %}
{% module Headline(headline) %}
{% end %}
</ul>
</body>
</html>
Finally, views.py, where you can define all your UI modules:
from tornado.web import UIModule
class Headline(UIModule):
def render(self, name):
return '<h1>%s</h1>' % name
UI modules are like "reusable templates", that accept parameters.