Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse a string from tag django

I have a custom template tag

{% perpage 10 20 30 40 50 %}

User can write his own numbers instead of this 10,20 etc. Also, the amount of these numbers is defined by user. How can I parse this tag and read this numbers? I want to use "for"-instruction

UPDATE:

@register.inclusion_tag('pagination/perpageselect.html')
def perpageselect (parser, token):
    """
    Splits the arguments to the perpageselect tag and formats them correctly.
    """
    split = token.split_contents()
    choices = None
    x = 1
    for x in split:
        choices = int(split[x])
    return {'choices': choices}

so, i have this function. i need to get arguments (numbers) from template tag, and convert them to integers. Then, i need to make a submit form for passing the choice like a GET parameter to URL (...&perpage=10)

like image 999
Max L Avatar asked Feb 01 '26 15:02

Max L


1 Answers

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 }}

like image 200
Alasdair Avatar answered Feb 04 '26 07:02

Alasdair