[Python] django模版中带参数调用任意函数的方法 →→→→→进入此内容的聊天室

来自 , 2021-04-27, 写在 Python, 查看 169 次.
URL http://www.code666.cn/view/14b7367a
  1. #template_filters.py
  2.  
  3. @register.filter
  4. def template_args(instance, arg):
  5.     """
  6.    stores the arguments in a separate instance attribute
  7.    """
  8.     if not hasattr(instance, "_TemplateArgs"):
  9.         setattr(instance, "_TemplateArgs", [])
  10.     instance._TemplateArgs.append(arg)
  11.     return instance
  12.  
  13. @register.filter
  14. def template_method(instance, method):
  15.     """
  16.    retrieves the arguments if any and calls the method
  17.    """
  18.     method = getattr(instance, method)
  19.     if hasattr(instance, "_TemplateArgs"):
  20.         to_return = method(*instance._TemplateArgs)
  21.         delattr(instance, '_TemplateArgs')
  22.         return to_return
  23.     return method()
  24.  
  25. # 在模版里面按照下面的方法调用
  26. {{ instance|template_args:"value1"|template_args:"value2"|template_args:"value3"|template_method:"test_template_call" }}
  27.  
  28. # 输出结果
  29. value1, value2, value3
  30. #//python/7616

回复 "django模版中带参数调用任意函数的方法"

这儿你可以回复上面这条便签

captcha