About me

Wednesday, September 26, 2018

python django (django template language 2)

Django Template Language

Tags
for
The for loop over each item in an array for example to display a list of athletes provided in athlete_list:

<ul>
{%for athlete in athlete_list%}
<li>{{athlete.name}}</li>
{%endfor%}
</ul>
if ,elif,and else
Evaluates a variable and if that variable is true the contents of the block are displayed


{% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
    Athletes should be out of the locker room soon!
{% else %}
    No athletes.
{% endif %}

in the above if athlete_list is not empty the number of athletes will be displayed by the {{athlete_list|length}} variable . Otherwise if athlete_in_locker_room_list is not empty the message "Athletes should be out..." will be displayed if both lists are empty "No athletes " will be displayed
you can also use filters and various operators in the if tag:
{% if athlete_list|length > 1 %}
   Team: {% for athlete in athlete_list %} ... {% endfor %}
{% else %}
   Athlete: {{ athlete_list.0.name }}
{% endif %}
most templates will return string so mathematical comparisons using filters will generally not work as you expect Length is an exception
Comments
the comment out part of a line in a template use the comment syntax{# #} for example this template would render as 'hello':
{#greeting#}hello
a comment can contain any template code invalid or not For example


{# {% if foo %}bar{% else %} #}

This syntax can only be used for single-line comments (no newlines are permitted between the {# and #} delimiters). If you need to comment out a multiline portion of the template, see the comment tag.
Template inheritance
The most powerful and thus the most complex - part of djangos template engine is template inheritance . template inheritance allow you to build a base skeleton template that contains all the common elements of your site and defines block that child templates can override

 Comments

 The method to comment out part of a line in a template we can use {# #}
by using this we can comment out for example

{#hello#}greetings
The template would render as 'greeting' a comment can contain any code invalid or not for example
{# {% if foo %}bar{% else %} #}
This syntax can only be used for single line comments (no newlines are permitted between the {#and#} delimiters  ) its used only for single line comments but to comment out multiline line comment we use {%comment%}and{%endcomment%} an optional note can be inserted in the first tag this is useful when commenting out code for documentint why the code was disabled .

<p>Rendered text with {{ pub_date|date:"c" }}</p>
{% comment "Optional note" %}
    <p>Commented out text with {{ create_date|date:"c" }}</p>
{% endcomment %}
comment tags cannot be nested

Template inheritance 

 as inheritance in other languages the template inheritance allows us to build a base skeleton template that contains all the common elements of our site and defines blocks that child templates can override
 its easiest to understand template inheritance y starting with an example

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="sidebar">
        {% block sidebar %}
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/blog/">Blog</a></li>
        </ul>
        {% endblock %}
    </div>

    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
this template will be our base class which is base.html its a simple html skeleton document that you might use for a simple two coloumn page its the job of child templates to fill the empty blocks with content
In this example the block tag defines three blocks that child templates can fill in all the block tag does is to tell the template engine that a child template may override those portions of the template
A child template might look like this :

{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <br />
<h2>
{{ entry.title }}</h2>
{{ entry.body }}<br />
{% endfor %}
{% endblock %}


More on template inheritance and django template language will be included in next pages till then thanks for reading this blog and kindly expecting your feed backs please reply on comment section and follow let me know your suggestions and follow me and share this blog





Monday, September 3, 2018

python django (Django Template Language)


Django Template Language

The template language as we explained earlier here we are going to learn more about template language Django template system is not simply python embedded into html this is by design the template system is meant to express presentation not programe logic the django template system provides tags which function similarly to some programming constructs an if tag for boolean tests a for tag for looping etc but these are not simply executed as the corresponding python code and the template system will not execute arbitrary python expressions

Templates
A template is simply a text file it can generate any text base format (HTML,XML, CSV,etc)
which contains variables which get replaced with values when the template is evaluated and tags which control the logic of the template

Here is an example
{%extends "base_generic.html"%}
{%block title %}{{section .title}}{%endblock%}
{%block content%}
<h1>{{section.title}}</h1>
{%for story in story_list%}
<h2><a href="{{story.get_absolute_url}}">{{story.headline|upper}}</a></h2>
<p>{{story.tease|truncatewords:"100"}}</p>
{%endfor%}
{%endblock%}

Variables
Variables look like this {{variable}} when the template engine encounters a variable it evaluates that variable and replaces it with the result variable names consist of any combination of alphanumeric characters and the underscore ("_") but may not start with an underscore The dot (".") also appears in variable sections although that has a special meaning as indiacated below importantly but we cannot have spaces or punctuations characters in variable names the dot are used to access attributes of a variable the above example {{section.title}} will be replaced with the title attribute of the section object
If you use a variable that doesnt exist the template system will insert the value of the string_if_invalid option which is set to ' ' (the empty string) by default note that var in a template expression like {{foo.bar}} will be intterpreted as a literal string and not using the value of the variable bar if one exists in the tempate context

Filters

the filters are used to modify variables to display here is an example for filter like this
{{name|upper}} this displays the value of the{{name}} variable after being filtered through the upper filter which converts text to uppercase by using a pipe (|) to apply a filter filters can be chained
the output of one filter is applied to the next {{text|escape|linebreaks}} is a common idion for escaping text contents then converting line breaks to <p> tags

some filters take arguments a filter argument looks like this {{bio|truncatewords:30}} this will display the first 30 words of the bio variable
there are about sixty builtin template filters you can read that in this link  built-in filter reference
some most commonly used filters are following
default
if a variable is false or empty use given default otherwise use the value of the example:


{{value|default :"nothing"}}
if value is not provided or is empty the above will display nothing
length
returns the length of the value this works for both strings and lists for example:

{{value|length}}
if value is ['a','b','c','d'] the output will be 4
filesizeformat
formats the value like a human readable file size (i.e '13 KB' , '4.1 MB','102 bytes',etc ) for example


{{value|filesizeformat}}
if value is 123456789, the output would be 117.7 MB you can also build custom template tags which will be explained in other posts

Tags

Tags look like this : {% tag %} tags are more complex than variables some create text in the output some control flow by performing loops or logic and some load external information into the template to be used by later variables 
some tags require beginning and ending tags {% tag %} ....... tag contents.....{%endtag%} 
there are many template tags you can find it in the given link as built-in tag reference
there are some commonly used tags which will be explained on next post thanks for viewing my post



MY friends i kindly expect your feedback to improve my posts please share and follow my blog if any doubts please comment