在Django模板中调用Python函数 [英] Calling Python function in Django template

查看:478
本文介绍了在Django模板中调用Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个django模板里面,我试图在一个模板变量上调用split函数,然后得到最后一个元素,所以我做了这样的事情:

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

不幸的是,它不喜欢分裂。有些人可能会建议我在视图中进行分割,但是我不知道如何做,因为我需要为所有的记录做。如果我可以在模板中做到这将会更容易。有没有办法这样做?

解决方案

不喜欢分裂是什么意思?它如何表现出不喜欢?



如果我记得正确,您不能传递任何可以在模板中使用的django模板和标识符的方法的任意参数,只能在模板中使用由az,AZ,0-9,下划线和点(其中点表示lookup:dictionary-> attribute-> method-> list-index)组成。



至少有四种方式来实现你想要的:




  • 使得适当准备好的数据可以作为模型的属性(或者是什么) ,通过预处理

  • 使数据可用作您的模型的方法,并确保该方法不需要参数,除了 self

  • 在视图中填充模型实例

     通讯通讯:
    setattr(通讯,'basepath',
    newsletter.NewsletterPath.split('/')[ - 1])$ ​​b $ b

    (或沿着这些线路)


  • 实现一个自定义过滤器标签,它将处理拆分(比您想象的更容易)


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?

解决方案

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)

这篇关于在Django模板中调用Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆