I have a Django template base.html:
// inside the javascript
var this_page = "{{ this_page }}";
// inside the HTML part
{% ifnotequal this_page "home" %}
...Some HTML...
{% endifnotequal %}
The part inside the javascript area is incorrect. Actually, Firebug shows me in the HTML tab:
var this_page = "home";
but if I look into the GET inside the Console tab, Firebug shows:
var this_page = "about";
which would be correct, but debugging shows that 'this_page' is set to 'home'.
I also tried it:
{% ifnotequal this_page "home" %}
do some javascript
{% endifnotequal %}
but that did also not work correctly.
What am I doing wrong?
EDIT: This problem only occurs when I access this page via a link. If I access the "about" page directly, I do not have this problem.
Testing on Ubuntu, Firefox 6.0.2, on 'runserver'
JavaScript is a client-side language. The HTML of your template is rendered by the python on server side so you cannot change rendered variable's value through java script code. In your case this_page is rendered html variable and var this_page = "{{ this_page }}"; defines a separate javascript variable and does not change the rendered html this_page variable. So firebug is correct.
You can use Ajax for this purpose if you want to dynamically change the rendered HTML.
The solution to the problem had (perhaps not surprisingly) nothing to do with the question. Apologies that I asked into the wrong direction.
Since I use jquery mobile, it behaved not as I expected: the body content (per default) is loaded per ajax on page change, while the head part is only loaded once.
The solution to the problem I have found here.
Related
I'm using Django and Python 3.7. I want to change the href in a template depending on whether a certain condition is satisfied (the user is viewing the page on a mobile device). If the user is using a regular device, the URL would be
{{ articlestat.article.path }}
Otherwise the path would be the above, except wiht the "www." replaced by "mobile.". What's the right way to do this? I have the below
{% if request.user_agent.is_mobile %}
<td align="center">Read Article</td>
{% else %}
<td align="center">Read Article</td>
{% endif %}
but it seems a little lengthy and I'm thinking there's a more concise way in Django to write all of the above.
I do not have a Django way of going about this at first glance but I do have a quick Javascript solution that you can have much more control over.
function redirect(btn, url) {
btn.on('click', function () {
window.location.href = url; // A string
})
}
var btn = <your btn>; // Use JQuery to get element as an ID
var url = <redirect url>;
redirect(btn, url);
I'm using the (awesome) Flask framework to build a website and I now have a problem with html not being rendered properly. I've got a line in my template with an if-else depending on whether the public variable is True:
{{ theInfo if public else '<span style="background-color: green;">this info is hidden</span>' }}
Unfortunately, this simply displays the html in the browser, instead of rendering it. Do I need to somehow let Jinja know that its html should be rendered?
All tips are welcome!
By default Jinja escapes the passed data. Therefore you need to explicitly tell Jinja that data is safe to use:
{{ theInfo if public else '<span style="background-color: green;">this info is hidden</span>' | safe }}
If you want to display different html based on a value you need to first send this value in your call to render_template
python
def view():
variablename = True
return flask.render_template('page.html', public=variablename)
To check this value you add an if statement inside curly brackets, see code below
html
{% if public %}
<p>Public is true!</p>
{% else %}
<span ..../>
{% endif %}
A good first step is to go through the tutorial by Miguel Grinberg. http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
I'd like to make a simple website running on the GAE framework/service. It's very small, and i don't really need the whole powerful Django framework, and thus i'm opting for the google-made Webapp2 framework, coupled with the Jinja2 templating langage.
I'm coming from a really bare-PHP-and-HTML-oriented background, so I have a hard time adjusting to the way a real framework works. My current greatest interrogation comes from how the templating system and the request handlers are working together, especially if the the page's template has several "dynamic" elements.
I'll first explain what I used to do in PHP, so you may better understand what i want to achieve.
Let's say I want a website with :
a page title depending on the page being visited, eg : "Mysite.com | Control Panel"
a dynamic menu bar, that may change depending on the user's profile or logged-in status
obviously, a page body that completely depends on the page being viewed
The way i'd do it in PHP is thus here compressed into a simple example, index.php:
<?php
/*here use the $_GET or $_POST variable, and the $_SESSION variable
to figure out who's connected, which page is being displayed,
and store those values in global variables, for the
included modules to use */
include('page_header.php'); // renders the whole <head> </head> tag and its content
echo "<body>";
include('views/menu.php'); //generates the menu, displays it
switch($page_name){
case "home":
include('home.php'); //renders the page body for the homepage
break;
case "articles":
include('home.php'); //renders the page body for the blog articles listing
break;
case "guestbook":
include('home.php'); //renders the page body for the guestbook
break;
}
echo "</body>";
Each included module, using variables from the script that called them (index.php), and the $_POST, $_GET, $_SESSIOn superglobals, figures out what to display, and renders it to HMTL. here index.php also does some kind of very basic routing, using the switch statement.
Now,back to webapp2 and jinja2 framework:
I understand that, to have a modular approach to build a web page with Jinja, you need to use block structures, and extend those blocks. Thus, to build a similar page to the previous PHP example, i made the following template base.html:
<html>
<head>
<link rel="stylesheet" href="/static/css/reset.css">
{% block title %}
{% endblock title %}
</head>
<body>
<div class="menu">
{% block menu %}
{% endblock menu %}
</div>
<div class="body">
{% block content %}
{% endblock content %}
</div>
</body>
</html>
What i don't understand, is how you you'll build the different Handlers that, in turn, generate the context that Jinja will use to render the blocks, and avoiding redundency.
**Also, can I use several different template files that, alone, extend only one block (eg: menu.html, header.html, body_home.html, body_articles.html, ...) **
You can use as a base to answer, this example, from a small example that almost taught me all i needed to know.
Thanks for any help provided, sorry for any grammatical errors, english's not my native tongue.
There's a feature in jinja2 called macros which is pretty much a parameterized include.
So if the includes should be parametized, you would do:
{% macro menu(params) -%}
do something
{%- endmacro %}
And call the macro in your template:
<div> menu('bar') </dib>
If it is not necesary to provide parameters just leave it as static html in the parent template.
For the handler you can follow App Engine hello world example, just use your link to guide you to load jinja's enviroment.
I know you want to translate the php example, but try to do as much logic as posible in your handler instead of the template.
To your second question, yes you can extend just one block if you want, and if you need the parents content there's a {{super()}} block to get them.
I'm trying to build a simple blog with Django, and now i'm stuck on something thats probably really easy to fix.
In one of my views, i'm loading all of the blogposts sorted chronologically, nothing strange there.
Now i'd like to load that page, and add an anchor-point to each post, so that they are indivudually reachable.
template:
{% for post in allPosts %}
<div id="post">
<h4>{{post.title}}</h4>
<br>
{{post.content}}
<br>
<i>{{post.datetime}}</i>
</div>
<br>
{% endfor %}
I'm using a blank url to load the index-page; so this view is reached from http://localhost:8000 in devmode.
Now, if i add an anchor-point (in lack of a better word..) to each of my posts, like:
modifying: <div id="post">
to <div id="post_{{post.id}}">
Should make every post, in that page, reachable via:
http://localhost:8000#post_1
..and so on..
Which works just fine, when the url is typed directly in the address-field of the browser, but when i try reaching it from a link from within the page itself, nothing happends..
Really grateful for any pointers, to where my problem might lie..
Get rid of the 'http://localhost' part. Just use the '#post_xx' part has the href.
i.e., I believe you need to do Post 35 when you create a link to an anchor within the same page
I am trying to create site navigation using AJAX. I have navigation menu with links to different views (using {% url name %} in template). The thing I am trying to do is to load the page content using AJAX. The page content I am trying to load is enclosed in content block ({% block content %}).
I also found this snippet http://djangosnippets.org/snippets/942/, but I want to use the views I have already defined and only get the content using ajax.
Any suggestions?
You should use django-pjax which is built exactly for that kind of thing.
All you will have to do is to, in the base template, include the whole page or just the block content based on whether the request is ajax or not.
django-pjax does the AJAX calls using the jQuery and manipulates history using HTML5 push state API, which is a very good way to do it and also gracefully degrades in IE older versions.
Template tags like {% block content %} are long gone by the time AJAX sees things. What you want to do is create a named <div> in your content block, like:
{% block content %}
<div id="content"></div>
{% endblock content %}
Then you can use something like this (jQuery) code to load the <div> when needed:
$("#content").load(url, data, loadComplete);
where url is the URL you want to load (HTML expected in return), data is the form data (if any; can be omitted), and loadComplete is the optional function to be called when the data is loaded, and is of the form function loadComplete(responseText, textStatus, XMLHttpRequest) {...}. Even if you don't want to use jQuery, you can get the non-minified jQuery source and see how they do it.