TurboGears provides a standard set of variables to all templates as an aid to template writers. You can easily add your own functions and variables to this standard set, check below for details.
Takes an iterator, loops forever over the passed in iterator. This is very similar to the itertools.cycle() method but it provides a way to get the current iterator value via the value attribute:
>>> from turbogears.view.base import cycle
>>> oe = cycle(('odd','even'))
>>> oe
None
>>> oe.next()
'odd'
>>> oe
'odd'
>>> oe.next()
'even'
>>> oe.next()
'odd'
>>> oe.value
'odd'
Shortcut to the standard urllib.quote_plus function.
Replaces special characters in string using the “%xx” escape. Letters, digits, and the characters “_.-” are never quoted. Also replaces spaces by plus signs, as required for quoting HTML form values. Plus signs in the original string are escaped unless they are included in safe, a string of characters that do not require escaping.
This function allows your absolute path URLs to work when the application’s root is moved. If, for example, you want your application to be rooted at /my_app, you set server.webpath to '/my_app/'. After doing this, tg.url('/') will return '/my_app/' and tg.url('/foo') will return '/my_app/foo'.
Query parameters for the URL can be passed in as a dictionary in the second argument or as keyword parameters.
To add your own atributes and methods, all you need to do is append a callable onto turbogears.view.variable_providers. This callable is passed a Bunch (a dictionary that has __getattr__ & friends so it can be treated like an object) containing the variables listed above. Simply update the Bunch with your custom attributes/methods and return it.
# This is in 'controllers.py' outside your Controller classes.
# Alternatively, put this in 'stdvars.py' and do "import projectname.stdvars"
import turbogears
def is_dead(animal):
if animal == "parrot":
return True
elif animal == "cat":
from random import choice
return choice([True,False])
else:
return False
def add_custom_stdvars(vars):
return vars.update({"is_dead": is_dead})
turbogears.view.variable_providers.append(add_custom_stdvars)
# is_dead will now be accessible as 'tg.is_dead' in your templates
Though this procedure may seem slightly arkward at first, it is much more flexible than just adding static values to the template environment. Using a callable you can add as many variables or functions to the template variables as you like, with just one callable, you just have to add more keys to the passed Bunch. Also, since add_custom_stdvars gets called on every request, the keys and values which you add can change dynamically from request to request, if necessary.