Render specific Jinja content blocks in main page upon button click - python

Hi guys as you will see below, I am a complete newbie to jinja blocks and how to manage them and would highly appreciate your help
main.html
<html>
<head><head>
<body>
<li>about us</li>
<li>Our services</li>
<body>
</html>
The idea is to render a jinja content block on li clicked in the main body:
so for example, if the user clicks on the li named "about us", I would like to render the content block named "about us" which extends this base template
And if the user clicks our services, I would like to render the content block named "our services" which extends this base template.
the about us block content is an HTML file and looks like the one below:
about-us.html
{% extends main.html %}
{% block aboutus %}
<p> ABOUT US INFORMATION</p> <!-- for example -->
{% endblock %}
the our services block content is an HTML file and looks like the one below:
ourservices.html
{% extends main.html %}
{% block ourservices %}
<p> OUR SERVICES</p> <!-- for example -->
{% endblock %}
Finally, I would like to know if it's possible to change the URL of my page when I go to any of these options:
from application import app
from flask import render_template, request, Flask
#app.route("/main.html")
def main():
return render_template("main.html", index=True)
so the idea is if I click on about us, the URL will change to main/about-us and should render the following:
and the URL looking like main/about-us
<html>
<head><head>
<body>
<p> About us</p>
<body>
</html>
and services should look like main/services
<html>
<head><head>
<body>
<p> OUR SERVICES</p>
<body>
</html>
I would highly appreciate your help!!!!

It's not clear to me if you intend for these to be distinct pages or just sections on the same page.
If sections on the same page, then why not just render all the content and hide the sections you don't initially need. When user clicks a button, you can then unhide the relevant section.

Related

How do you render a variable as html using flask?

Using flask, I'm passing in a list of dictionaries to one of the pages. One of the variables contains html text (ex:var x = <h1>hello</h1>). How would I get it to display as hello rather than just print out "<h1>hello</h1>"? Here's my code so far (post.description has the html variable; It's equal to <h1>hello</h1>):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
{% for post in posts %}
<p>{{post.title}}<p>
{{post.description}}
{% endfor %}
</body>
</html>
You can use safe to render the HTML code with Jinja.
Example: {{ post.description | safe }}

Django: Inject a string variable from Views.py with HTML and Django template tags into HTML file

So this is my issue: I have a Python string that contains both HTML and Django Template Tags and want to inject it into a base HTML file when I go to that page. Although, when I go to the page, all the HTML renders, but the Django Template Tags do not, and are treated literally as strings?
Here is a simplified example of the issue:
Views.py
def page(request, code):
html = {
'code': code
'html': """<p>Hello world {{ code }}</p> <script src="{% static 'appName/javascript_code_example.js' %}"></script>"""
}
return render(request, 'base.html', html)
base.html
{% load static %}
...
{{ html | safe }}
...
And all I will see when I run the app on my local machine with python3 manage.py runserver and go to the URL that renders base.html is Hello world {{ code }}, and the Javascript code is not executed. Instead of {{ code }} I'd like to see the actual value of the 'code' key in the html dictionary in the Views.py file.
If my base.html file is as follows:
{% load static %}
...
<p>Hello world {{ code }}</p>
<script src="{% static 'appName/javascript_code_example.js' %}"></script>
...
Then the Javascript will be enabled and I will see Hello world value_of_code_variable on the screen.
you have to load the python script that has the template library functions.
Also, Why are you rendering a string into html as opposed to creating an html template? (html file with template syntax)?
The Django template engine will not render (parse) template code inside injected strings. For this to happen, you have to manually render the template code by either:
instantiating a Template object and passing the resulting string to your base.html,
or ideally by moving the value of your html context variable to a template file, and using render_to_string().
If you decide to go for the last one, you should definitely consider using the include template tag in your base.html (instead of manually rendering using render_to_string()), as it reduces the amount of manual work and is the preferred way of rendering template code inside another template.
You can use file writing to do this task.
Make a newfile.html in templates folder and you can do thusly
Views.py
html_tag = "{% extends \"yourapp/base.html\"%}"+"{% block content %}"
html_tag +="<p>Hello world {{ code }}</p> <script src=\"{% static \"appName/javascript_code_example.js\" %}\"></script>"
html_tag +="{% endblock content %}"
html_file = open('yourapp/templates/yourapp/newfile.html', "w")
html_file.write(html_tag)
html_file.close()
html = {
'code': code
}
return render(request, r'yourapp\newfile.html', html)
In base.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Your base code</p>
<!--The part of code you want to retrieve from views.py file-->
{% block content %}{% endblock content %}
</body>
</html>

Django appends white space to views

So I have recently started looking into the Django framework, but it appends some white space in the top of my views even though the layout.html and layout.css is the same for each view.
layout.html
<html>
<head>
<meta charset="utf-8" />
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'layout.css' %}" />
<link href='https://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' />
</head>
<body>
<div class="content">
<div class="navbar">
Homepage.
Home
Projects
About
</div>
<div class="text">
{% block stuff %}
{% endblock %}
</div>
</div>
</body>
</html>
This is my views
def index(request):
return render(
request,
'home/index.html',
{
'greetings': "Welcome to my site!",
}
)
def about(request):
return render(
request,
'home/about.html',
{
'greetings': "Welcome to my site!",
}
)
home/index.html and home/about.html both look like
{% extends "layout.html" %}
{% block stuff %}
{{ greetings }}
{% endblock %}
about page pushed down
As seen in the image the view for the about.html page is push down, and I really cannot figure out why.
After inspecting the elements I found that for the about page, the header is added to the body tag.
inspecting the elements
Anyone who can help me out?
This is most likely because of CSS. To find out where the space is coming from, click on inspect element and choose select an element to inspect it. Then slightly move the mouse around the page until you find that space and click on it. You can then find out where the space is coming from in the Styles tab.
Also make sure there are no <br>tags in your html template
The view is certainly not the culprit here, it's just a python function which takes in a request and returns a response. The HTML looks fine too, check your CSS once again(or post it here) or you can always check the source code on your browser and inspect element the page through the Developer tools to check where the whitespace is coming from.

How to extend to 'base.html' template styles in Django

I work with templates in my application. I have the main part of the website styled in base.html, being the files that always will be the same (header, menu, footer...) properly coded in 'base.html' and also with the styles linked to it (in a link rel="stylesheet").
When I try to use the base template as it is, a base template, it works well while it lets me add content between de {% block content %} and also shows the 'permanent' parts (menu, header etc), but there have no style (CSS) on it. How could I also extend to these stylesheet to load the CSS styles??
Help would be appreciated, thank you.
EDIT 2: Here's my base.html head content:
<head>
<meta charset="utf-8">
{% load staticfiles %}
<title>{% block title %}Index{% endblock %}</title>
{% block style_base %}
<link href="{% static 'css/styles.css' %}" rel="stylesheet">
{% endblock %}
<meta name="description" content="{% block description %}{% endblock %}">
<link href='https://fonts.googleapis.com/css?family=Roboto+Mono:400,700,300' rel='stylesheet' type='text/css'>
<script src="static/myapp/jquery.min.js" type="text/javascript"></script>
<script src="static/myapp/main.js" type="text/javascript"></script>
</head>
This works on base.html, it gets the correct styles. However, when trying to get the same styles in the common part with another template, it doesn't gets the styles. The template code starts like this:
{% extends "base.html" %}
{% load staticfiles %}
{% load i18n %}
{% include "base.html" %}
{% block title %}{% trans "Main index" %}{% endblock %}
{% block content1 %}
It gets all the correct HTML from base.html but unstyled. I also try delete the 'include' tag or changing its position but there's no result. What can be wrong? Thank you.
Also, the console tells me this:
Not Found: /list/static/myapp/styles.css
[25/Mar/2016 01:03:03] "GET /list/static/myapp/styles.css HTTP/1.1" 404 3414
When I refresh the page (list is the page where there is the template I wanna get the styles from base) it keeps telling me this. List is not a directory in my project, but the /static/myapp/styles.css path is correct. What happens?
You have to call the CSS files within the base.html, so when you extend the base.hml in your other pages, the CSS will be called.
For me, I usually do this:
I have Head.html I call all Javascripts and CSS files I am using in the website inside it like this:
for CSS:
<link rel="stylesheet" type="text/css" href="/static/styles/example.css"/>
for javascript:
<script type="text/javascript" src="/static/js/example.js"></script>
then, in each page in the website, after the title tag I include this Head.html like this:
{% include "Head.html" %}
When you do this in every page, the CSS and javascripts files will be seen in all the pages and callable.
Also, the main urls.py file should be like this: "the answer is from here"
urlpatterns = [ # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
On top of your html file add this:
{% extends "base.html" %}
It should work, maybe the css path is wrong, or try to delete your {%block style_base%}

Detect mobile browser (not just iPhone) in python view

I have a web application written in Django that has one specific page I'd like to implement a mobile version of the template (and slightly different logic) for. I'd like to be able to implement it ala this sudo code:
def(myView)
do some stuff
if user-is-on-a-mobile-device:
do some stuff
return (my mobile template)
else:
do some stuff
return (my normal template)
I don't have a huge amount of time and I'm pretty early on in my coding learning curve :) - I found what looks to be a very powerful pluggable app called bloom for getting mobile device capablities - http://code.google.com/p/django-bloom/wiki/BloomDevice
However it seems to make a request via JSON to get lots of device specs I don't need, which seems a bit inefficient to me.
Does anyone have a suggest simpler method? My detection doesn't need to be 100%, just iPhone, iPod, android, and mainstream devices...
Does the http_user_agent string have some kind of mobile flag I can check for?
Update:
I just found: http://code.google.com/p/minidetector/
Which seems to do exactly what I want, I'm going to test now. Feel free to tell me i'm wrong!
best practice: use minidetector to add the extra info to the request, then use django's built in request context to pass it to your templates like so.
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view_on_mobile_and_desktop(request)
.....
render_to_response('regular_template.html',
{'my vars to template':vars},
context_instance=RequestContext(request))
then in your template you are able to introduce stuff like:
<html>
<head>
{% block head %}
<title>blah</title>
{% if request.mobile %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-mobile.css">
{% else %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-desktop.css">
{% endif %}
</head>
<body>
<div id="navigation">
{% include "_navigation.html" %}
</div>
{% if not request.mobile %}
<div id="sidebar">
<p> sidebar content not fit for mobile </p>
</div>
{% endif %>
<div id="content">
<article>
{% if not request.mobile %}
<aside>
<p> aside content </p>
</aside>
{% endif %}
<p> article content </p>
</aricle>
</div>
</body>
</html>
go for the fork of minidetecor called django-mobi, it includes documentation on how to use it.
https://pypi.python.org/pypi/django-mobi

Categories