Miguel Costa
"A serious and good philosophical work could be written consisting entirely of jokes."
Django4FrontEnd
Autor: Carlos Batman
Django4FrontEnd
Author: Carlos Batman
Templates em Django - Django4FrontEnd
Fat models
Thin views
STUPID TEMPLATES
fonte: Vokal
Templatetags em Django - Django4FrontEnd
Templatetags em Django - Django4FrontEnd
fonte: Django Project Docs
Expressões que podem ser usadas em templates django para gerar ou adaptar conteúdo.
Ligam funções a templates
Templatetags em Django - Django4FrontEnd
# templatetags/appname_tags.py
from django import template
# ... any other imports you need...
register = template.Library()
@register.inclusion_tag('dumbtemplate.html')
def obter_transformada(*args):
    '''
    ...
    '''
    fonte: Django Project Docs
{% load appname_tags %}
<!-- template.html -->
{% obter_transformada 'a' 'b' 'c' %}
    Templates em Django - Django4FrontEnd
the Django template system is not simply Python embedded into HTML.
This is by design: the template system is meant to express presentation, not program logic
fonte: https://docs.djangoproject.com/en/1.8/topics/templates/
Templatetags em Django - Django4FrontEnd
@register.filter
def as_comma_separated_string(list_of_stringable_items):
    """
    Returns a string composed of all items on a list, separated by a comma and a space
    .. warning: Each item on the list must be convertible to a string without error
    :param      list_of_stringable_items:  The list of stringable items to be enumerated
    :type       list_of_stringable_items:  list (or something enurable, but list is the expected type)
    :returns:   a string containing all items on the list, separated by commas
    :rtype:     { string }
    :Example:
    ..code-block:: html
    
    <!-- if some list is ['a', 'whatever'] -->
    {{ some_list|as_comma_separated_string }}
    <!-- will return 'a, whatever' -->
    """
    return ', '.join([str(item) for item in list_of_stringable_items])
Exemplo 1 - Filtro
Templates em Django - Django4FrontEnd
Templatetags em Django - Django4FrontEnd
{{ variavel|filtro }}
{{ variavel|filtro:"parametro" }}
@register.filter
def filtro(value, arg=None):
    '''
    Returns a string with ' filtrada' appended to the string representation of 'value'.
    If an additional argument is sent, 
    it also appends ' com ' and the value of 'arg' to the returned value 
    :param: value   The value to be filtered
    :type: value    String, or any other value that can be converted to a string
    :param: arg     An additional argument
    :type: arg      String, or any other value that can be converted to a string   
    :returns:       A string similar to the first parameter's value and some additional content
    :rtype:         String
    .. code-block:: html
    {{ 'text'|filtro:'whatever' }}  
    
    '''
    if not arg:
        return "%s filtrada" % (value)
    else:
        return "%s filtrada com %s" (value, arg)Templatetags em Django - Django4FrontEnd
{% simples %}
{% simples "par1" 2 %}
@register.simple_tag
def obter_transformada(*args):
    '''
    Returns a string with 'Transformada fica: ' and the value(s) of all parameters  
    appended to it, separated by spaces.
    :returns:       A string similar to the first parameter's value and some additional content
    :rtype:         String
    .. code-block:: html
    {% obter_transformada 'It is' 'done' 'ok not yet' 'now it is' %}  
    
    '''
    return " ".join([str(arg) for arg in args])fonte: Django Project Docs
Templatetags em Django - Django4FrontEnd
@register.inclusion_tag('dumbtemplate.html')
def obter_transformada(*args):
    '''
    ...
    '''
    return {
        "quote": " ".join([str(arg) for arg in args])
    }fonte: Django Project Docs
Mesma coisa que 'simples', mas:
<!-- dumbtemplate.html -->
<p>
  Your answer: {{ quote }}
</p>Templatetags em Django - Django4FrontEnd
@register.assignment_tag
def obter_transformada(*args):
    '''
    Returns a string with 'Transformada fica: ' and the value(s) of all parameters  
    appended to it, separated by spaces.
    :returns: A string similar to the first parameter's value and some additional content
    :rtype:   String
    .. code-block:: html
    {% obter_transformada 'It is' 'done' as transformada %}
    {{ transformada }}
 
    '''
    return "quote": " ".join([str(arg) for arg in args])
    fonte: Django Project Docs
Mesma coisa que 'simples', mas:
Será substituída pela simple_tag, que pode ser usada desta maneira a partir do django 1.9
Templates em Django - Django4FrontEnd
from classytags.core import Tag, Options
from classytags.arguments import Argument
from django import template
register = template.Library()
class Hello(Tag):
    name = 'hello'
    options = Options(
        Argument('name'),
        'as',
        Argument('varname', required=False, resolve=False)
    )
    def render_tag(self, context, name, varname):
        output = 'hello %s' % name
        if varname:
            context[varname] = output
            return ''
        else:
            return output
register.tag(Hello)Tag + Assignment Tag
from classytags.helpers import InclusionTag
from classytags.arguments import MultiKeywordArgument
from classytags.core import Options
class IFrameTag(InclusionTag):
    """
    Renders an IFrame HTML element with a specific src, and also width and height, which are both set to 0 by default.
    
    :Example:
    
    .. code-block:: html
       {% iframe src='//slides.com/costaman/djadefdoc/embed' width=500 height=400 %}
       <!-- will output --> 
       <iframe src='//slides.com/costaman/djadefdoc/embed' width='500' height='400' frameborder='0'></iframe>
    """
    name = 'iframe'
    template = 'someapp/iframe.html'
    options = Options(
        MultiKeywordArgument('options', required=False),
    )
    def get_context(self, context, options):
        default_options = {
            'src': '',
            'width': 0,
            'height': 0
        }
        default_options.update(options or {})
        options = default_options
        return options
register.tag(IFrameTag)<!-- someapp/templates/someapp/iframe.html -->
<iframe src="{{ src }}" width="{{ width }}" height="{{ height }}" frameborder="0"></iframe>By Miguel Costa
Django templates are one of the key features of Python's (possibly) most popular web framework. In order to understand them, and set them apart from a typical html (or text) file, one must grasp two concepts: context and templatetags. Through this presentation, Carlos Batman provides a brief introduction (in Portuguese) to django templates with some practical examples.