Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I often pass inline data from server -> client JS using a meta tag. In rails3 it would look like:

<meta name='blah' content="<%= @data.to_json %>" />

However this has always seemed unclean to me. Does anyone else have a better, alternative method of inlining data? I'd rather not use inline scripts for the exact reason they mention.



Use data-* attributes [1], or print it in a script tag with a text/anything type:

    <script type="text/json" id="mydata">
        { data: "..." }
    </script>

    var data = JSON.parse($('mydata').textContent)
[1] https://developer.mozilla.org/en-US/docs/HTML/Global_attribu...


If you put it in a script tag you need to ensure you escape </script>. Though, it is probably safer to escape <, >, and & just to be sure.


The </script> issue is why JSON and Javascript both allow you to escape the slash character with a backslash.

So just going <\/script> is enough.



Can you give it directly to the JS working on that data by setting a var (var x = <%= @data.to_json %>;) or passing it in as a parameter to an initializing function call (APP.init(<%= @data.to_json %>);)? Edit: 1. I hope it's not user generated data. 2. The output in this case wouldn't need to be JSON syntax, it could be object literal notation, saving space on all those double quotes but I doubt you have a helper method available for that.


you can put anything inside class attribute

<div id="data" class="{json: 'x'}"/>

you can mix actual classes with JSON, just put JSON at the end:

<div class="header inline {json: 'x'}"/>

CSS selectors will work just fine




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: