Best practice for passing server-side variables to javascript?

Davy8 picture Davy8 · May 8, 2011 · Viewed 8.7k times · Source

I've tried 2 ways that both work but neither feel very clean.

The first is to have some inline javascript that accepts the variable from the view template like:

var x = {{ myServersideVariable }}; 

(In my case I'm using Jinja2 but same thing would apply to Django templates, Razor in .NET MVC3, Twig in PHP or any number of view templating engines).

Obviously the unclean part about this that there's javascript in the html page rather than in a separate file.

The other option I've used is to have a hidden field populated server side and then consumed on the Javascript end. That feels slightly more clean, but not completely and it's also a bit cumbersome to write.

Is there a better solution or are those pretty much my only options?

P.S.
I'm aware of JSON and in fact I do sometimes have to resort to the first solution if I need to pass something other than primitives. So bonus points for a solution that supports passing JSON objects without having javascript on the page.

Answer

Raynos picture Raynos · May 8, 2011

There are only two correct ways to inject data from the server into javascript.

You either expose the data as a service. You can have a REST service or whatever you like and then query it with ajax to extract data from it.

The other option is to inject the data into the HTML. You want to use JavaScript to progressively enhance your page. So that data already needs to exist in the HTML, and your JavaScript will extract it from the HTML.

Now if your going for a JavaScript heavy application which can't be supported without JavaScript then you want your data to be a REST service.

You do not want to inject it into a serialized hidden field because then your html markup does not have the semantics of the data. You do not want inject it directly into a var x = ... statement because then your compiling your JavaScript on the fly. This breaks the seperation of concerns.