I'm trying to use inheritance in jinja2 on google app engine. But I haven't managed to do it so far. Could you please point me to what I am doing wrong?
Here is my base.html:
{{text}}
{% block title %}
Failure
{% endblock %}
this template is extended by the title.html:
{% extends "base.html" %}
{% block title %}
World!!
{% endblock %}
Both templates are in the same directory /templates/wiki.
This is how I load templates and render base.html:
import os
import jinja2
import webapp2
template_dir = os.path.join(os.path.dirname(__file__), '../templates/wiki')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)
class MyHandler(webapp2.RequestHandler):
def get(self):
templ = jinja_env.get_template('base.html')
self.response.out.write(templ.render(text = 'Hello,'))
The supposed output is
Hello, World!!!
but I can get just:
Hello, Failure
Jinja2 version is 2.6.
You have to render title.html instead of base.html.
Related
Hi thank you for helping, I'm poor in coding.
To point: I'm doing a Django project that pass data form data-base to front-end; but right now i can't even pass anything views of Django into templates, I suspect i'm passing the wrong variable types; please do comment on your thought.
This is my code on views.py:
from django.shortcuts import render
def index (requset):
return render(requset,'myapp/index.html') # link to be able open frountend
def testdex(requset):
text = "hello world"
context ={'mytext' : text }
return render(requset,'myapp/inculdes.html', context)
so my variable will be pass into inculdes where extend to index page
This my codes on in inculdes.html:
{% exntends "myapp/index.html" %}
{% block includes %}
{{ mytext }}
{% endblock includes %}
this my code on index.html:
<body>
{% block includes %} {% endblock includes %}
</body>
Thanks again on giving me your time to help me and appreciate it if could write me some code because try fix this for whole week
You can try something like this:
views.py
from django.template.response import TemplateResponse
def testdex(request, template_name="myapp/includes.html"):
args = {}
text = "hello world"
args['mytext'] = text
return TemplateResponse(request, template_name, args)
includes.html
{% extends "myapp/index.html" %}
{% block includes %}
{{ mytext }}
{% endblock includes %}
And make sure you have set path for templates in settings.py
When you do {% block content %}{% endblock content %} you are telling Django that you want to be able to overwrite this section. Please note the word content can be anything to reflect what you want to overwrite.
When you do {{ variable }} you are telling Django that you want to pass a Context. In this example, variable I want to pass is called Title as the key and Portfolio as the value. Context is a dictionary that you pass in views.py like this:
def portfolio_home(request):
return render(request, 'portfolio/work.html', {'title': 'Portfolio'})
Let's say I want to pass a context (or a variable) into my base template. In this example, I want to pass title in the title tag of the head section of my base template.
In the html file for base.html, you need to have something like this:
<!DOCTYPE html>
<html lang="en">
{% load staticfiles %}
<head>
<title>{{ title }}</title>
...........
</head>
</html>
In the urls.py of my project and other apps that I want to pass a title into this, I should create the view like this:
def portfolio_home(request):
return render(request, 'portfolio/work.html', {'title': 'Portfolio'})
I found out why Django can't pass variables to HTML because;
I didn't have my apps url activated the function/model in views
I feel so embarrasses, for such simple mistakes.
All I need to do is add this code in my apps url
urlpatterns = [
path('', views.timedex, name='timedex'), #need add this
path('', views.index, name='index'),
]
Add {{block.super}} before {% endblock includes %}
I am building a chatbot. There are few child templates like login.html, messages.html, transaction.html, etc. I want to append these templates in base.html dynamically. I am extending base.html in all these templates. My problem is only one template is rendered at a time. Is there any solution for appending these templates one after another? I have used {%include%} but it's a static approach. I need dynamic.
printer.py looks like -
#app.route('/respond', methods=['GET','POST'])
def respond_def():
message = request.form['message_input']
if message == "l":
return render_template('printer/login.html')
elif message == "t":
return render_template('printer/transactionID.html')
base.html looks like -
//some code here
<li>
{% block template %}{% endblock %}
</li>
//some code here
message.html looks like -
{% extends "base.html" %}
{% block template %}
<div> Message template called </div>
{% endblock %}
I resolved it.
I made a list of templates in printer.py and then appended those templates in base.html whenever user asked for it.
printer.py
dictionary = []
// append name of template in this whenever needed.
return render_template('printer/base.html', dictionary=dictionary)
base.html
{% for d in dicts %}
{% set template = 'printer/' + d + '.html' %}
// can add conditions for different templates
{% include template %}
{% endfor %}
I have a base.html which i extends to other pages also. In few pages , images are displayed but in few it does not. other than images , everything like header , section are displayed.
{% load staticfiles %}
some more --like header , section
<footer>
<div id="footer">
{% block footer %}
<img src ="../../static/blog/images/git.png">
<p>© 2016 shankar.</p>
{% endblock %}
</div>
My template file
{% extends 'blog/base.html' %}
{% block content %}
<h1>Articles for {{ year }}</h1>
{% for article in article_list %}
<h4>{{ article.headline }}</h4>
<h5>Posted by <strong>{{ article.reporter }}</strong>
on {{article.pub_date|date:"F j, Y"}}</h5><hr/>
{% endfor %}
{% endblock %}
url `
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'article/(?P<year>[0-9]{4})/$', views.year_archive, name='year_archive'),
url(r'article/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive, name='month_archive'),
url(r'(?P<article_id>[0-9]+)/$',views.article_detail,name='article_detail'),
url(r'^comment/(?P<article_id>[0-9]+)/$' ,views.comment,name='comment'),
url(r'^contact',views.contact,name='contact'),
]`
views
ef year_archive(request,year):
#year=str(pub_date)[0:4]
year=year
try:
article_list = Article.objects.filter(pub_date__year=year)
except Article.DoesNotExist:
raise Http404("Article does not Exists")
context = {'year':year, 'article_list':article_list}
return render(request, 'blog/year_archive.html',context)
It's because you're not using the correct src. You should let the static function handle the static files. When the url changes ../../ will not be correct anymore, depending on the path.
You should configure the static directory in your settings.py file and then reference your image like this:
<img src ="{% static 'blog/images/git.png' %}"></a>
You're loading staticfiles but you never actually use it, you should use the static template tag
"../../static/blog/images/git.png"
should be
{% static 'blog/images/git.png' %}
You should also use the url template tag..
I am trying to get Django user's group in HTML for an if tag. This is what I tried:
{% ifequal user.groups.all.0 'ABC' %}
{% endif %}
But this is not working. What other way is there?
Try this:
{% for group in request.user.groups.all %}
{% if group.name == 'ABC' %}{% endif %}
{% endfor %}
Or
{% if request.user.groups.all.0.name == 'ABC' %}{% endif %}
You have to access the current user object from the request context variable. For this, make sure that django.template.context_processors.request is in your template settings.
request.user.groups.all.0 returns a Group model object, so you have to compare against the name field.
I think you will have to use a little Python here. For example, a custom template tag:
#register.filter(name='has_group')
def has_group(user, group_name):
return user.groups.filter(name=group_name).exists()
And in your template:
{% if request.user|has_group:"ABC" %}
...
{% endif %}
(Source: http://www.abidibo.net/blog/2014/05/22/check-if-user-belongs-group-django-templates/)
But maybe you should actually use permissions here.
https://docs.djangoproject.com/en/1.8/topics/auth/default/#authentication-data-in-templates
Edit: Here is a more complete example of the custom template tag:
settings.py:
INSTALLED_APPS = [
...
'yourapp',
...
]
Filesystem:
yourproject/
manage.py
yourproject/
settings.py
wsgi.py
...
yourapp/
__init__.py
templatetags/
__init__.py
yourapp_extras.py
...
yourapp_extras.py:
from django import template
register = template.Library()
#register.filter(name='has_group')
def has_group(user, group_name):
return user.groups.filter(name=group_name).exists()
Template:
{% load yourapp_extras %}
{% if request.user|has_group:"ABC" %}
...
{% endif %}
To get a more thorough understanding of this, I highly recommend reading Django's excellent documentation.
<h1>{{ user.groups.all.0 }}</h1>
{% if user.groups.all.0.name == 'Team2' %}
<h1>YES</h1>
{% else %}
<h1>NO</h1>
{% endif %}
Here, the user.groups.all.0 gives you the first group assigned to the user.
For eg. if the logged in user has groups assigned to him as- 'Team2', 'Programmer', 'Beginner'.
Then {{user.groups.all.0}} will print Team2.
I've used it to print and check the logged in user's group in html template.
OR
{% if request.user|has_group:"mygroup" %}
<h1>Has group mygroup</h1>
{% endif %}
Also works fine in django v1.11. This will check if the current user has 'mygroup' assigned to it or not.
However you'll need to add
from django import template
from django.contrib.auth.models import Group
register = template.Library()
#register.filter(name='has_group')
def has_group(user, group_name):
group = Group.objects.get(name=group_name)
return True if group in user.groups.all() else False
inside a group_check.py in below file structure
--app
|templates
|templatetags
|-- group_check.py
I'm a newbie experimenting with Flask/Jinja2 and SQL-Alchemy.
I have a question about html output when using Jinja2 templating.
My view function looks like this:
from app import app
from flask import render_template
from init_database import init_db
from app.models import Provider
#app.route('/update')
def update():
provider = Provider.query.get_or_404(1)
return render_template("update.html", provider=provider)
And my template looks like this:
{% extends "layout.html" %}
{% block content %}
<div class="page">
<ul>
{ % for provider in prov %}
<li>
{{ provider.nzbprovider }}
{{ provider.rssfeed }}
</li>
{ % endfor %}
</ul>
</div>
{% endblock %}
When I run the app, the out looks like this in the browser:
{ % for provider in prov %}
Peter Johnson
Michael Manning
{ % endfor %}
Why does it display the Jinja tags? What have I forgotten?
You have spaces in the Jinja tag delimiters: Change { % (with a space) to {% (with no space)