Calling Python function in Django template

自古美人都是妖i 提交于 2019-12-21 02:21:27

问题


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:

{{ newsletter.NewsletterPath.split('/').-1 }}

Unfortunately, it doesn't like the split. Some might suggest that I do the split in the view, but I'm not sure how to do that because I need to do it for all of the records. It would be much easier if I could do it in the template. Is there a way to do this?


回答1:


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)



回答2:


From the django book:

Note that you do not include parentheses in the method calls. Also, it’s not possible to pass arguments to the methods; you can only call methods that have no required arguments.

So, if you want to call a method without arguments from a template, it's fine. Otherwise, you have to do it in the view.




回答3:


Templates are deliberately not able to do such stuff. The purpose is to prevent you from putting your business logic in templates, which are meant to deal only with the layout.

So a possible way to do this is to define a NewsletterPathLastElement(self) function in your newsletter Model, and call that from the template.




回答4:


Yes, as others have said, you shouldn't really be doing it in the templates.

But if you want to, then you need to define a filter and load it in the template and use it.



来源:https://stackoverflow.com/questions/2115869/calling-python-function-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!