This question already has answers here:
Passing HTML to template using Flask/Jinja2
(7 answers)
Closed 4 years ago.
I'm new to flask, but want to integrate some HTML capabilities from other libraries together with the templating power of flask. In playing around with variables, I'm not able to understand the different behavior for rendering HTML. Sometimes I can get the HTML rendered if I pass it directly to a view as a variable:
body = a bunch of HTML
#app.route('/')
def index():
return '''
{}
'''.format(body)
However, if I try to pass this to a template using the {{ body }} variable, I don't get the HTML rendered. Instead, I will see the raw HTML on the page.
#app.route('/')
def index():
return render_template("index.html", b = body)
In the "index.html" file, I call this with the {{ b }} template syntax. Here, I get the raw HTML though. I feel there's just one little piece I'm missing. Here's what I see for each approach respectively.
Jinja will escape all strings that it parses to avoid accidentally injecting HTML into your templates. To mark variables as "safe to use as-is", you need to use the safe template filter.
{{ b|safe }}
>>> b = 'Example'
>>> render_template_string('{{ b }}', b=b)
'<a href="#">Example</a>'
>>> render_template_string('{{ b|safe }}')
'Example'
Related
this is the exercise(you can use only two html templates (the index and the movie). When the user navigates to a movie specific page the description and title must be read from a file called {movie_id}.txt within the project dir and then passed to movie template.)
i tried this ===>>
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/index")
def index():
return render_template("index.html")
#app.route("/marvel")
def marvel():
with open("marvel.txt") as file:
return render_template("movie.html", text=file.read())
however it only printed the html codes inside the text file and didnt use it as html codes.
If I understand you correctly, the text file contains html tags, which are automatically escaped within the template. Use the Jinja2 filter safe within the template to suppress this behavior.
{{ text | safe }}
An alternative to declare content outside of the template as safe is the following. You can find the documentation here.
from flask import Markup
#app.route("/marvel")
def marvel():
with open("marvel.txt") as file:
html = Markup(file.read())
return render_template("movie.html", text=html)
Note that the default behavior has been implemented for security reasons and you are aware of what the contents of the text file can do within your page.
Perhaps your task allows you to reconsider your data structure and application design so that you can format the html entirely within the template and not within a plain text file.
I just want to slice a string on django in two parts, passing a caracter like "|"
Example: 2007-007134|10003L
Part 1: 2007-007134
Part 2: 10003L
I tried somethings but without success
Someone can help me?
Create a custom template tag. They are basically python code which you can execute from inside the html templates (when using defult Django templating engine).
You can read more about them here:
https://docs.djangoproject.com/en/3.1/howto/custom-template-tags/
https://www.codementor.io/#hiteshgarg14/creating-custom-template-tags-in-django-application-58wvmqm5f
I solved according Maciej Rogosz recommended:
Custom Template Tag
First: I created the folder templatetags inside of my app, after that create a empty ini.py and finally created my custom_tag.py:
from django import template
register = template.Library()
#register.filter(name='split1')
def split1(value, key):
return value.split(key)[1]
#register.filter(name='split2')
def split2(value, key):
return value.split(key)[0]
In my tamplate I have to load the template tags
{% load custom_tags %}
And call my custom_tags: split1, split2
{{ instance.mat_code|split1:"|" }}
{{ instance.mat_code|split2:"|" }}
That is it, python + django = Magic
Tks to everyone for your help
Ref1: https://www.w3schools.com/python/ref_string_split.asp
Ref2: https://www.codementor.io/#hiteshgarg14/creating-custom-template-tags-in-django-application-58wvmqm5f
I am familiar with flask, and trying hands on bottle module. I wanted to have a single base.tpl file which can have an editable body and the other tpl files could extend this base file and edit in its body to change the content. Like in flask, using jinja, we could use {% block bodyContent %}{% endblock %} and insert the html body content later when needed. How can we achieve the same with bottle module?
Bottle comes with jinja2 support, out of the box. Here's a toy example, just to illustrate. Note that you may prefer to use Bottle's jinja2_view rather than return a template directly.
from bottle import jinja2_template
app = Bottle()
home_template = '''
{{greeting}} - Thanks for stopping by.
'''
app.route('/')
def home():
return jinja2_template(home_template, greeting='Hello!')
You can find examples of more advanced usage here.
Actually bottle comes with this solution built into it's own template engine.
https://bottlepy.org/docs/dev/stpl.html#template-functions
include(sub_template, **variables)
Render a sub-template with the specified variables and insert the resulting text into the current template. The function returns a dictionary containing the local variables passed to or defined within the sub-template:
% include('header.tpl', title='Page Title')
Page Content
% include('footer.tpl')
rebase(name, **variables)
Mark the current template to be later included into a different template. After the current template is rendered, its resulting text is stored in a variable named base and passed to the base-template, which is then rendered. This can be used to wrap a template with surrounding text, or simulate the inheritance feature found in other template engines:
% rebase('base.tpl', title='Page Title')
<p>Page Content ...</p>
This can be combined with the following base.tpl:
<html>
<head>
<title>{{title or 'No title'}}</title>
</head>
<body>
{{!base}}
</body>
</html>
This question already has an answer here:
Reference template variable within Jinja expression
(1 answer)
Closed 7 years ago.
I need to pass dynamic values to my python view. My HTML looks like:
<a href="{{ url_for('refresh_page',
lang_code=g.current_lang,
feature='a+z+',
cata={{ att.get('url_slug')}})}}"
>
I need to pass this {{ att.get('url_slug')}} to my Flask View:
#app.route('/<lang_code>/category/<string:feature>/<string:cat>/<int:pag e>')
def navigate_page(feature, page):
But its not working. I just started working on views, what I am doing wrong. Please help!!
The url_for is already a template function, so no need to escape the parameter:
<a href="{{ url_for('refresh_page',
lang_code=g.current_lang,
feature='a+z+',
cata=att.get('url_slug')) }}">
This question already has an answer here:
Django - How to make a variable available to all templates?
(1 answer)
Closed 6 years ago.
I am trying to pass variables (browser variable) to all my templates in my app. Any advice on how to get it to work?
View:
def browser(request):
primary_cat_list = Categories.objects.order_by("category")
subcat_list = SubCategories.objects.order_by("sub_category")
product = Productbackup.objects.order_by("website")
browser = list(chain(primary_cat_list, subcat_list, product))
return render_to_response('reserve/templates/base.html', locals(), context_instance=RequestContext(request))
Template:
{% for prod in browser %} {{ prod }}, {% endfor %}
You, my friend, are in the market for Context Processors.
From a blog entry written by a far nimbler and erudite technical writer than I:
What are template context processors?
Django’s context processors are a facility that allows you to provide data and callbacks to your templates.
You can do so in one of two ways:
On an individual request basis: by passing a custom Context value to your render_to_response() call
Globally: by creating a context processor method that accepts a HttpRequest object as input, and returns a payload or callback, then
registering the context processor in your settings.py, then providing your render_to_response() call with the built-in RequestContext attribute
instead of your own (you can always extend RequestContext to add more data on an individual request basis of course).
If that approach for passing data to templates sounded absurd and obfuscated to you, you’re not alone. The complexity involved in such a simple operation is unwarranted and counter-productive, but every system has its shortcomings.
The official documentation is here:
https://docs.djangoproject.com/en/dev/ref/templates/api/
So but yeah, I have been programming with Django for a while, and one of the reasons I really like solving problems w/ it is because it is almost Byzantine in its complexity, but not in a domineering sort of way. It has a ton of geegaws and doodads that may not immediately appear useful; each of these either comes in extremely handy when you need it, and it will stay out of your way if not.
The upshot here for you is: context processors are a fine example of those. Yes.
Currently you're passing locals() as the variable scope which should include browser aswell, but I find the use of locals() very ugly.
Personally I always prefer a pattern like this instead:
def browser(request):
context = RequestContext(request)
primary_cat_list = Categories.objects.order_by("category")
subcat_list = SubCategories.objects.order_by("sub_category")
product = Productbackup.objects.order_by("website")
browser = list(chain(primary_cat_list, subcat_list, product))
context['browser'] = browser
return render_to_response('reserve/templates/base.html', context_instance=context)
I can give you an example of my code, that works fine. Here is the file named context_processors.py:
context_processors.py
def base(request):
user = request.user
#======================
#Login form
#=====================
# here is the code for login user or check if he is logged in already
return {
'user': user,
}
and that's, part of my base.html (a template that I use wor all my pages)
base.html
{% if user.username %}
<h3>
Welcome {{ user.username }}
</h3>