Tuesday, November 30, 2010

Re: Javascript and template rendering problem

On 29/11/10 20:03, Anderson Goulart wrote:
> Hi,
>
> How can I render to a javascript code a variable set in a view?
> I tried {{ variable }} but it returns nothing in the html source code.
> When I put this {{ variable }} outside <script> tags it works perfectly.
> Any clues?
>

Since you do say it returns nothing, it's probably not what's wrong
(depending on how you inspected the source) but one thing to bear in
mind is escaping, remember to use

var foo="{{bar|escapejs}}";

to avoid little surprises on embedding stuff into js [1].

Another alternative to embed the value on the normal html side and pull
the value out with javascript/jquery. Not incredibly efficient, but
useful if you want a per-template-rendered value, but want to keep .js
files separate (embedded js in script tags has subtleties*) and unmunged
by any django templating.

* e.g. browsers do tend to muddle through given all sorts of peculiar
input of course, but beware xhtml vs. html - for xhtml, you must use
CDATA inside the script tag (or properly escape significant chars) [2],
whereas html 4 says to treat script specially [3] so you get away
without that, but then watch out for accidental embeddings of "</" which
will end your script. (draft html5 apparently [4] allows embedded "</",
ho hum))

[1] http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#escapejs

[2] http://www.w3.org/TR/xhtml1/#h-4.8
[3] http://www.w3.org/TR/REC-html40/types.html#type-cdata
[4]
http://stackoverflow.com/questions/4029341/dom-parser-that-allows-html5-style-in-script-tag

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment