Iterate over json string items in jinja2 - python

Hi I need to send data in string format to my jinja templates, and the render them. The only way I found is to format my data as JSON and send it as a string to the renderer. But I don´t know how to use it in the templates, it seems that the tojson filter it´s not for this purpose, because it keeps rendered a string.
to keep it simple I'm doing something similar to:
import json
a = {"a":1,"b":[1,2,3,4]}
response = json.dumps(a)
in template:
{{ response }}
{{ response|tojson }}
both give a string response, not a dict or an object that I can use to render based on the values

You can import json to use it's load function to load it into jinja.
from json import loads
environment = jinja2.Environment(whatever)
environment.filters['load'] = loads
{{ response|load }}
Reference:
Import a Python module into a Jinja template?

Related

HTML not rendering well when using markdown2 converted

I'm working on a Django project in Python and using markdown2 to convert some markdown text into HTML but it appears to not be doing it well or I'm missing something in the code.
In my views.py file I'm using a custom function to extract some text from an .md file in markdown format and with the markdown2 module I try pass it on to the HTML template like so:
text = markdown2.markdown(util.get_entry(entry))
But in the HTML, if I inspect the source code what is supposed to render as HTML comes out like this:
<h1>HTML</h1>
Am I missing something in my code? Is the error on the HTML template or in my views.py file?
Thanks in advance!
You probably have rendered the content in the template with:
{{ text }}
Django will by default escape the content, and thus replace < with <, etc.
You can make use of the |safe template filter [Django-doc] to prevent this:
{{ text|safe }}

Python - Update Jinja2 template multiple times and then render it

I would like to update template several times and then render it. From Jinja2 documentation, I have found that:
generate()
For very large templates it can be useful to not
render the whole template at once but evaluate each statement after
another and yield piece for piece. This method basically does exactly
that and returns a generator that yields one item after another as
unicode strings.
It accepts the same arguments as render().
This is my code and I don't know how to output/render template.
template_render.py
from jinja2 import Environment, Template, FileSystemLoader
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
template = env.get_template('template_file.html')
template.generate(title='Lorem ipsum')
template.generate(subtitle='Dolor sit amet')
#How to render it now?
template_file.html
{{ title }} {{ subtitle }}

API Integration in Django

I am trying to use the OpenDOTA API in my pet project. At the moment, I am having problem displaying the content of the API into my CBV.
My views.py:
from django.views.generic import TemplateView
import requests
import json
# Create your views here.
class HeroList(TemplateView):
template_name = 'dota/heroes.html'
url = 'https://api.opendota.com/api/heroes'
r = requests.get(url)
r.text
result = r.json()
I am lost on how to call the json in my HTML. I've tried running the same code in python IDLE, and when I type the "result" and hit enter, it gives my the dict. Any idea on how should I display the dict into my template?
What you need to do is first dump your json to a dictionary format.
import json
from django.shortcuts import render
rdict = json.loads(r.json())
return render(request, template_name=<template name>, context=rdict)
All this reside insides your function inside your views.py
Now after this using Django template language - https://docs.djangoproject.com/en/1.11/topics/templates/
You can render data in keys in your dictionary to your template.
If you mean accessing the result in html, then below is a sample.
choices = {'key1':'val1', 'key2':'val2'}
Here's the template:
<ul>
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
</ul>
from this answer how to access dictionary element in django template?

How to display object in template Flask as json?

I have a route method:
#app.route('/add', methods=['GET'])
def add_view():
return render_template('add.html', categories=api.categories())
Then I tried to display categories as JSON inside template add.html:
{{ categories | json }}
It does not work
I find it hard to understand exactly what you're looking for here so I'd like to see more details but here's an answer based on what I think you're asking for (I'll edit this to suit your needs / remove this comment entirely if things change).
You're invoking api.categories() and are looking to render this as JSON on your HTML template, yes?
OK what I'd recommend here is to ensure that api.categories() is returning an instance of dict. For example, your api.categories() call should return something like this:
{
"testKey1": "testValue1",
"testKey2": "testValue2"
}
Now to render this as JSON in your HTML template. You can import the json module in your Flask module using the following import:
import json
Now your return statement in your add_view method will be as follows:
return render_template('add.html', categories=json.dumps(api.categories()))
You can now do something like as follows in your HTML template:
<script>
document.write("{{categories}}");
<script>
This should render your JSON for you just fine.

How to parse "2015-01-01T00:00:00Z" in Django Template?

In my Django html template, I get my SOLR facet_date result using haystack in the format
"2015-01-01T00:00:00Z". How can I parse it in format "01/01/2015" in my template?
My template is
{{ facets.dates.created.start }}
What "|date:" option should I add to my template?
Thanks!
If your date is a ISO string instead of a Python datetime.datetime, I guess you will have to parse it on the view or write a custom filter:
# yourapp/templatetags/parse_iso.py
from django.template import Library
import datetime
register = Library()
#register.filter(expects_localtime=True)
def parse_iso(value):
return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ")
Then at the template:
{% load parse_iso %}
{{ value|parse_iso|date:'d/m/Y'}}
[edit]
got this error Exception Type: TemplateSyntaxError at /search/ Exception Value: 'parse_iso' is not a valid tag library: Template library parse_iso not found
Make sure you follow the code layout prescribed in the docs:
yourapp/
__init__.py
models.py
...
templatetags/
__init__.py
parse_iso.py
views.py
Your country may use m/d/Y (01/01/2015 is ambiguous, I suggest using an example like 31/01/2015 so it is clear if the first number represents day or month).
If {{ facets.dates.created.start }} is a datetime object then you can use
{{ facets.dates.created.start|date:"SHORT_DATE_FORMAT" }}
In case you are providing a string you can create a template filter to convert the string to datetime object and apply the date filter
#register.filter
def stringformat(value, args):
return datetime.strptime(value, args)
In the template:
{{ facets.dates.created.start|stringformat:"%Y-%m-%dT%H:%M:%SZ"|date:"SHORT_DATE_FORMAT" }}
You can use Django template tags for this. You need to use {{my_date|date:"some_format"}} which takes "my_date" as the argument (it should be a date object) to "date" tag and then formats it based on the given format.
{{facets.dates.created.start|date:"d/m/Y"}}

Categories

Resources