Calling Python function in Django template

后端 未结 4 2009
一向
一向 2021-02-09 12:52

Inside a django template I\'m trying to call the split function on one of the template variables and then get the last element, so I did something like this:

{{          


        
4条回答
  •  暖寄归人
    2021-02-09 13:43

    What do you mean by "it doesn't like the split"? How does it manifest its dislike?

    If I remember correctly, you can not pass any arbitrary arguments to methods, that are called from the django template and the identifiers, that can be used in the templates can only consist of a-z, A-Z, 0-9, underscores and dots (where dots signify lookup: dictionary->attribute->method->list-index).

    There are at least four ways to achieve what you want:

    • make the appropriately prepared data available as an attribute of your model (or whatever that is), by pre-processing it
    • make the data available as a method of your model and make sure, that the method takes no required arguments, besides self
    • populate the model instances in the view

       for newsletter in newsletters:
            setattr(newsletter, 'basepath',
                    newsletter.NewsletterPath.split('/')[-1])
      

      (or something along these lines)

    • implement a custom filter tag, that will handle the split (easier, than you might think)

提交回复
热议问题