Import functions into templates

Problem: How can I import a python module in template?

Solution:

While you write templates, inevitably you will need to write some functions which is related to display logic only. web.py gives you the flexibility to write large blocks of code, including defining functions, directly in the template using $code blocks (if you don’t know what is $code block, please read the tutorial for Templator first). For example, the following code block will translate a status code from database to a human readable status message:

  1. def status(c):
  2. st = {}
  3. st[0] = 'Not Started'
  4. st[1] = 'In Progress'
  5. st[2] = 'Finished'
  6. return st[c]

As you do more web.py development, you will write more such functions here and there in your templates. This makes the template messy and is a violation of the DRY (Don’t Repeat Yourself) principle.

Naturally, you will want to write a module, say displayLogic.py and import that module into every templates that needs such functionalities. Unfortunately, import is disabled in template for security reason. However, it is easy to solve this problem, you can import any function via the global namespace into the template:

  1. #in your application.py:
  2. def status(c):
  3. st = {}
  4. st[0] = 'Not Started'
  5. st[1] = 'In Progress'
  6. st[2] = 'Finished'
  7. return st[c]
  8. render = web.template.render('templates', globals={'stat':status})
  9. #in the template:
  10. $def with(status)
  11. ... ...
  12. <div>Status: $stat(status)</div>

Remember that you can import more than one name into the globals dict. This trick is also used in importing session variable into template.