Search code examples
javascriptruby-on-railsrubytemplate-engine

rhtml to template for javascript


I'm working on a project with an old version of rails (1.2.6) and no javascript templating system. I want to render the same HTML on the server (e.g. in an rhtml view) and also on the client (e.g. when the user dynamically adds a row to a table).

So, for example, I have a partial that renders a row of input fields:

<tr><td><input /></td></tr>

This works great on the server. My plan was to render it in a display: none div for jQuery to find and clone when the user wants to add a row.

Unfortunately, when I render just a <tr> node in a div, predictably, the DOM doesn't include those elements. This jQuery clone approach can't work because of that behavior.

What can I do to share the code that generates the <tr> between the server and the client?


Solution

  • The problem you're probably having is that <div> is not a permitted parent for a <tr>:

    Permitted parent elements

    table, thead, tfoot, tbody

    so the browser will correct your broken <div><tr>...</tr></div> HTML into something you can't use. Using style="display: none" merely hides your <div> from the user, it won't hide the <div> from the browser.

    The usual way to sneak HTML fragments past the browser is to use a <script> with a non-HTML type as the container. You want something like this to get to the browser:

    <script id="pancakes" type="text/x-template">
        <tr><td><input /></td></tr>
    </script>
    

    Then you can work with $('#pancakes').html() as plain text in your jQuery.


    You might want to talk to someone about upgrading to a more recent version of Rails, who knows what sorts of holes and bugs are in such an ancient and unsupported version of Rails. The upgrade will only get harder as time passes.