Skip to content

Instantly share code, notes, and snippets.

@jlfwong
Created May 10, 2012 15:02
Show Gist options
  • Save jlfwong/2653732 to your computer and use it in GitHub Desktop.
Save jlfwong/2653732 to your computer and use it in GitHub Desktop.
ENV server->js data pattern
Why this is useful:
1. All data in ENV is coming from the server, so it's easy to differentiate data coming from the server and static data when reading through JS.
2. If you put the {{ env_js }} in the root template, it'll be usable by in all templates that inherit from it. That means you don't need to adjust the template to share data to the client-side.
3. Only one new global variable instead of one per thing coming from the server.
class SomeHandler(request_handler.RequestHandler):
def get(self):
user_data = user_models.UserData.current()
# If I want to propagate more data to the clientside, all I have to do is add to this dict
env_js = {
"user_data" : user_data.user_id if user_data else None
}
self.render_jinja2_template('template.html', {
"env_js" : jsonify.jsonify(env_js, camel_cased=True)
})
{% if env_js %}
<script>var ENV = {{ env_js }};</script>
{%- endif %}
console.log(ENV.userId);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment