Methods of calling arbitrary functions with parameters in Django template

From , 3 Years ago, written in Python, viewed 217 times.
URL https://pastebin.vip/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

Reply to "Methods of calling arbitrary functions with parameters in Django template"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website