TemplateTAGS em Django (e ClassyTags)

Django4FrontEnd

 

Autor: Carlos Batman

TemplateTAGS in Django

Django4FrontEnd

 

Author: Carlos Batman

Templates em Django - Django4FrontEnd

Fat models
Thin views
STUPID TEMPLATES

fonte: Vokal

Conteúdo

  • O que é uma templatetag?
    • Que tipos há?
  • Criação de templatetags
    • ClassyTags
  • Exemplo prático: iFrame
  • Erros comuns

Templatetags em Django - Django4FrontEnd

Templatetags em Django - Django4FrontEnd

Expressões que podem ser usadas em templates django para gerar ou adaptar conteúdo.

Ligam funções a templates

 

  • {{variável|filtro}}
  • {% tags %} (template próprio? acesso a contexto?)

{% templatetag %}

Ativação de templatetags

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):
    '''
    ...
    '''
    
  1. Criar pasta templatetags em aplicação django
  2. Adicionar ficheiro chamado __init__.py
  3. criar ficheiro para tags (normalmente appname_tags.py)
  4. Adicionar aplicação django ao INSTALLED_APPS  em settings.py
  5. adicionar E registar tags
  6. carregar as tags no template desejado
{% 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

{% exemplos %}

@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

Tipos de Templatetag

Templates em Django - Django4FrontEnd

{{ filtro }}

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)

{% simples %}

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])

{% de_inclusao %}

Templatetags em Django - Django4FrontEnd

@register.inclusion_tag('dumbtemplate.html')
def obter_transformada(*args):
    '''
    ...
    '''
    return {
        "quote": " ".join([str(arg) for arg in args])
    }

Mesma coisa que 'simples', mas:

  • o resultado é exibido num formato definido por template!
  • é preciso retornar dicionário que será o contexto desse template
<!-- dumbtemplate.html -->
<p>
  Your answer: {{ quote }}
</p>

{% de_associacao as x %}

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])
    

Mesma coisa que 'simples', mas:

  • o resultado é associado a uma variável de contexto em vez de aparecer diretamente na 'página'

Será substituída pela simple_tag, que pode ser usada desta maneira a partir do django 1.9

ClassyTags

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)

ClassyTags

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)

Exemplo - IFrameTag

<!-- someapp/templates/someapp/iframe.html -->
<iframe src="{{ src }}" width="{{ width }}" height="{{ height }}" frameborder="0"></iframe>

Templatetags in Django

By Miguel Costa

Templatetags in Django

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.

  • 401