Am 24.10.2010 14:24 schrieb [email protected]:
In my attempts to solve this problem, I'd also tried to write a custom
decorator to do this ... but didn't get that to work for a variety of
reasons - some certainly due to the fact that I don't yet understand
TurboGears fully enough! ;)

I think the real problem is that this stuff is not yet documented good enough. How about the following solution?

-----------------------------------------------------------

from tg import json_encode, tmpl_context
from tg.decorators import Decoration
from tg.render import _get_tg_vars


class expose_jsonp(object):

    def __init__(self, callback=None, exclude_names=None):
        if callback is None:
            callback = 'callback'
        if exclude_names is None:
            exclude_names = []
        if 'tmpl_context' not in exclude_names:
            exclude_names.append('tmpl_context')
        self.callback = callback
        self.exclude_names = exclude_names
        self.exclude_callback = 'callback' in exclude_names

    def before_validate(self, remainder, params):
        if self.exclude_callback:
            tmpl_context.callback = self.callback
        else:
            tmpl_context.callback = params.pop(
                'callback', self.callback)

    def __call__(self, func):
        deco = Decoration.get_decoration(func)
        deco.register_hook(
            'before_validate', self.before_validate)
        deco.register_template_engine(
            'text/javascript; charset=utf-8',
            'jsonp', '', self.exclude_names)
        return func


def render_jsonp(template_name, template_vars, **kwargs):
    callback = tmpl_context.callback
    for key in _get_tg_vars():
        del template_vars[key]
    return '%s(%s)' % (callback, json_encode(template_vars))


from myapp.config.app_cfg import base_config
base_config.render_functions['jsonp'] = render_jsonp

-----------------------------------------------------------

You can provide a default name for the callback in the decorator that can be overwritten by the client with the "callback" parameter unless you set exclude_names=['callback'].

-- Christoph

--
You received this message because you are subscribed to the Google Groups 
"TurboGears" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/turbogears?hl=en.

Reply via email to