[Django]-Parse a string from tag django

3👍

As of Django 1.4, you can define a simple tag that takes positional or keyword arguments. You can loop through these in the template.

@register.simple_tag
def perpage(*args):
    for x in args:
        number = int(x)
        # do something with x
    ...
    return "output string"

When you use the perpage tag in your templates,

{% perpage 10 20 30 %}

the perpage template tag function will be called with the positional arguments "10", "20", "30". It would be equivalent to calling the following in the view:

 per_page("10", "20", "30")

In the example perpage function I wrote above, args is the ("10", "20", "30"). You can loop through args, convert the strings to integers, and do whatever you wish with the numbers. Finally, your function should return the output string you wish to display in the template.

Update

For an inclusion tag, you don’t need to parse the token. The inclusion tag does that for you, and provide them as positional arguments. In the example below, I’ve converted the numbers to integers, you can change it as necessary. I’ve defined a PerPageForm and overridden the __init__ method to set the choices.

from django import forms
class PerPageForm(forms.Form):
    perpage = forms.ChoiceField(choices=())

    def __init__(self, choices, *args, **kwargs):
        super(PerPageForm, self).__init__(*args, **kwargs)
        self.fields['perpage'].choices = [(str(x), str(x)) for x in choices]

@register.inclusion_tag('pagination/perpageselect.html')
def perpage (*args):
    """
    Splits the arguments to the perpageselect tag and formats them correctly.
    """
    choices = [int(x) for x in args]
    perpage_form = PerPageForm(choices=choices)
    return {'perpage_form': perpage_form}

Then in your template, display the form field with {{ perpage_form.perpage }}

Leave a comment