On Tue, Dec 20, 2011 at 09:07:58AM -0800, Wyatt Baldwin wrote:
> In an earlier version of my code, I did some dynamic JavaScript 
> configuration using Mako constructs:
> 
>     # app.mako
>     <script>
>         % if something:
>             // set some JS var
>         % endif
>         var x = '${some_var_from_view}';
>         var y = ${something_that_is_specific_to_this_request(request)};
>     </script>
> 
> Now I do something like this:
> 
>     # helpers.py
>     def get_js_config(request):
>         config = {
>             # whatever request-specific config you need
>         }
>         return literal(json.dumps(config))
> 
>     # app.mako
>     <script src="main.js"></src>  ## Load main JS function
>     <script>
>         main(${h.get_js_config()});
>     </script>

json.dumps() is insufficient quoting, if you're letting user-provided
content into your config dict.

Consider what happens when it tries to quote a string containing

  "</script><script>alert('0wn y00');</script>"

> I don't know if that is be applicable to your situation, but maybe you 
> could save the config object as a global that you can reference in 
> subsequent AJAX calls.
> 
> If I were going to go with the template approach, I'd set one config var 
> and reference that in the rest of the code rather than doing a bunch of 
> interpolation:
> 
>     # snippet.js
>     (function () {
>         var config = ${js_config};  // js_config is a JSON string
>         // ...
>         if (config.xyz) {
>             // do stuff
>         }
>     }());
> 

Marius Gedminas
-- 
Emacs can be like an autistic child, refusing to accept change but showing
more than a touch of genius in how it handles the familiar routine.
        -- Stephen J. Turnbull

Attachment: signature.asc
Description: Digital signature

Reply via email to