I have a Django template file that has a couple of enormous strings in it (images encoded in Base64). When I use the Django templating engine, it chokes and takes 5 minutes to render the template. Is there a way to exclude a part of a template, with something like:
{% ignore %}
<img src='....'>
{% endignore %}
Does this exist?
Use verbatim tag!
From django docs https://docs.djangoproject.com/en/dev/ref/templates/builtins/#verbatim
verbatim
Stops the template engine from rendering the contents of this block
tag.
A common use is to allow a JavaScript template layer that collides
with Django’s syntax. For example:
{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}
Related
I am trying to make a blogging website. I know django provides argument templates like
{% include images.html with value=sense %}
The above code directly works in HTML and hence everything works. The images are stored in a backend database and connected to everystory by some logic. The user can use the names of the images and call whenever they need to use it
When I try the above code directly in the backend it doesn't work because I think once something is rendered then it doesn't rerender by django HTML
I wish to paste some form of links in the django story backend. such that when it renders in HTML automatically the page should show pics in the appropriate place. If anyone has any idea how to do this kindly let me know.
So when loading stories in the database the user can put some form of links for images in the database and while rendering all images come in a certain format as specified in the block in the blog.So there can be any number of images and the count is not longer fixed as shown in the pics below where I am trying to render a image called sense from the backend which doesn't work.. whereas it directly works in the frontend.
<p>{{object.story_title}}</p>
<p>{{MEDIA_ROOT}}</p>
<p>{{object.story}}</p>
{% include "blogdescription/image.html" with value=sense %}
Thank you for your time.
with regards
Let me start saying that doing exactly what you want is not possible because Jinja will compile and render {{object.story}} and not its content (the include). It does not seem possible to use nested Jinja syntax to load any resources, includes, extends, urls, etc.
Which explains why when you place the include in the template it works but does not inside your model field.
What seems possible is to load an HTML image with a explicit URL to the resource, lets say, the content inside your text field is:
<div style="display: flex; justify-content: center; align-items: center;">
<img src="/static/myimage.jpg" alt="Object Image">
</div>
Template.html (source):
{% block content %}
{{obj.title}}
<br>
{{obj.body|safe}}
{% endblock %}
Alternatively, it is possible to generate a HTML file to render dynamically based on Object.field. Note that this solution is a heavy load on the server, for every request will generate a dynamic file to be rendered.
Obj field value:
{% extends 'base.html' %}
{% block content %}
{{obj.title}}
<hr>
{% include 'includes/image.html' %}
{% endblock %}
views.py:
def story(request, id):
obj = Story.objects.get(id=id)
f = open(f'templates/generated/dynamic_template.html', 'w+')
f.write(obj.body)
f.seek(0)
return render(request, 'generated/dynamic_file.html', {'obj': obj})
How to render jinja code on template?
For instance, I have a route that need to render jinja code on the given HTML template like this:
from app import app
from flask import render_template
from jinja2 import Template
#app.route('/View/Package')
def getView():
HtmlDesc="""
<div class="codehilite"><pre><span></span><span class="p">{{</span><span class="n">cookiecutter</span><span class="o">.</span><span class="n">repo_name</span><span class="p">}}</span><span class="o">/</span><span class="p">{{</span><span class="n">cookiecutter</span><span class="o">.</span><span class="n">repo_name</span><span class="p">}}</span><span class="o">/</span><span class="p">{{</span><span class="n">cookiecutter</span><span class="o">.</span><span class="n">repo_name</span><span class="p">}}</span><span class="o">.</span><span class="n">py</span>
</pre></div>
"""
return render_template('package.html', html=Template(HtmlDesc).render())
On the template, I tried to escape jinja code with {% raw %}..{% endraw %} and {% filter escape %} .. {% endfilter %} as documented here but it still does not work:
<h1>Project Description</h1>
<div class="project-description">
{% raw %}{% filter escape %}{{html|safe}}{% endfilter %}{% endraw %}
</div>
</div>
With exception:
TemplateSyntaxError: unexpected '<'
I know the error is at {{</span><span... and class="p">}}, value of HtmlDesc, therefore I am looking for a proper way to escape these kind of characters of jinja in order to render this jinja code on template correctly. Thanks.
Added
What I am trying to achieve is I want the html and jinja code of HtmlDesc to be interpreted and render properly on web browser. In my real application, the text above is not a fixed value as in above example snippet, it reads value from text file README which includes inside python package and converted into HTML code. The example text above it is read from python package cookiecutter.
Add a | safe to the end of whatever you want to display. It will render it out. Make it a string too.
Inside the template you seem to be missing the |safe in the {{ }} inside the Markup
Also you have to remove the Template() to make sure that the whole string is escaped
I'm building a site where users can view their posts Like this. After building the quizzes portion, I tabbed to "blogs" where I realized I needed to import the blogs template to use it.
I'm using the quiz template already like this
{% extends '../main/base.html' %} {% block title %}View Quizzes{% endblock %} {% block content %}
but I need to access the blog template as well. How can I do this? Thanks!
You can include the blog template into the main one like:
{% include "path/to/blogs.html" %}
It's best to have a main template which includes blogs, quizzes... (instead of inheritance)
You don't need django to do this.
I am using template to render basic html in django and specify link as below.
<li>Geometry</li>
I want to hide this link based on condition using model information.
Does anyone know how to do this?
You can surround the html in an if statement using the Django template language:
{% if object.something %}
<li>Geometry</li>
{% endif %}
You can use operators, filters or complex expressions if object.something is not a boolean
Django has an if template tag, see:
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#if
from the docs:
{% if not athlete_list %}
There are no athletes.
{% endif %}
I'm working on a simple blog app in Django, and i'm having trouble figuring out how to dynamically generate the five most recent posts in a side bar. Each of my views are class based and they extend a generic template, each view maps to one template which I believe is the correct way to do it. I've looked for a way to do this using template tags, but it seems Django doesn't like you to put any logic inside of your templates.
The problem I believe is that I want this to exist within my base.html because I want the recent posts to be displayed site-wide, is a view even supposed to map to your base.html or does that cause problems, i'm pretty new with this. I don't know how to approach this, whether i'm supposed to create a new view for base.html or if I should use my template tags, or if I should extend an existing view(but if I do that it won't be site wide?).
I essentially want the following(they're ordered in reverse chronological order)
{% for post in post_list[:4] %}
{{ post.title }}
{% endfor %}
You can use a template tag. More specifically, an inclusion tag is what you need. This allows you to insert a rendered snippet anywhere inside your template via a small view-like piece of code.
For example, create a templatetags/blog_tags.py file (it's important that you create the templatetags folder within your app; Django searches for them here by default) in your blog app and add the following:
from django import template
register = template.Library()
#register.inclusion_tag('blog/snippets/recent_posts.html')
def render_recent_blogposts():
return {
# This is just an example query, your actual models may vary
'post_list': BlogPost.objects.all().order_by("published_on")[:4]
}
now create a blog/snippets/recent_posts.html template (it can be anywhere as long as it mathecs the #register.inclusion_tag(...) above.):
<ul>
{% for post in post_list %}
<li> {{ post.title }}</li>
...
{% endfor %}
</ul>
finally, in your original template, you can now render your template tags:
<aside>
{% load blog_tags %}
{% render_recent_blogposts %}
</aside>