Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Better Practice for Templates / Reusable HTML?

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #37894
    TheLeggett
    Member

    Howdy,

    In an effort to write less repetitive code, I’ve developed a questionable practice for javascript templating (or rather, jQuery). I’m curious to see if anyone else could shine some light on if this approach is acceptable, or if there is a better way to go about what I’m attempting to do.

    Here’s a specific (simplified) case:

    • There is a table with 2 columns: Name, Eye Color
    • Initially, there are 0 rows below the table header.
    • There is a “New Row” button.
    • Clicking the “New Row” button creates a row with two cells. The Name cell has a text input. The Eye Color cell has select input.

    The html used to generate the new rows is what interests me. Until recently, I’ve used get requests to load templates, or I’ve added new elements to the DOM via jQuery (ie: .html(‘

    etc

    ‘)).

    Requests can be a huge performance hinderance, and don’t make sense in many basic cases like this. Writing html in js is frustrating, and usually means that if markup changes in the project, it needs to be changed in several locations.

    What I’ve been doing
    To make things easier for myself, I’ve been adding templates to the actual page markup. These templates are hidden with CSS. These templates are saved to a variable in javascript, and then cloned whenever they’re needed.

    For example:

    var $table_row_template = $('tbody#table_row_template tr'); // This tbody has a class with display:none;

    function add_table_row() {
    var $clone = $table_row_template.clone();
    $('tbody#actual_content').append($clone);
    }

    This approach let’s me accomplish my goals of:

    1. No extraneous requests
    2. Only write the code once (usually stored in a partial in the app)

    Apologies for the sort of lengthy explanation. This sort of stuff isn’t really an area I’m very comfortable in, and I thought there might be a better way of going about doing this that doesn’t involve hiding pointless markup… Thank you in advance for your time and help!

    (Also, if an actual code example would help illustrate the case here, please let me know and I’ll try to whip something up.)

    #102193

    That’s what Twitter do with modal windows in Bootstrap, so although this is slightly different, I don’t think it’s that bad of an idea.

    #102227
    TheLeggett
    Member

    Thank you for the responses. There are definitely some better ways to think about this issue :)

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.