Search code examples
javascripthtmlajaxdryhtml-generation

HTML that's both server-side and javascript generated - how to combine?


I'm usually a creative gal, but right now I just can't find any good solution. There's HTML (say form rows or table rows) that's both generated javascript-based and server-sided, it's exactly the same in both cases. It's generated server-sided when you open the page (and it has to stay server-sided for Google) and it's generated by AJAX, to show live updates or to extend the form by new, empty rows.

Problem is: The HTML generation routines are existing twice now, and you know DRY (don't repeat yourself), aye? Each time something's changed I have to edit 2 places and this just doesn't fit my idea of good software.

What's your best strategy to combine the javascript-based and server-sided HTML generation?

PS: Server-sided language is always different (PHP, RoR, C++).

PPS: Please don't give me an answer for Node.JS, I could figure that out on my own ;-)


Solution

  • Here's the Ruby on Rails solution:

    Every model has its own partial. For example, if you have models Post and Comment, you would have _post.html.erb and _comment.html.erb

    When you call "render @post" or "render @comment", RoR will look at the type of the object and decide which partial to use.

    This means that you can redner out an object in the same way in many different views.
    I.e. in a normal response or in an AJAX response you'd always just call "render @post"

    Edit:
    If you would like to render things in JS without connecting to the server (e.g. you get your data from a different server or whatever), you can make a JS template with the method I mentioned, send it to the client and then have the client render new objects using that template. See this like for a JS templating plugin: http://api.jquery.com/category/plugins/templates/