Created
May 10, 2012 15:02
-
-
Save jlfwong/2653732 to your computer and use it in GitHub Desktop.
ENV server->js data pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% if env_js %} | |
<script>var ENV = {{ env_js }};</script> | |
{%- endif %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log(ENV.userId); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment