Generate identical tables, but with different content

Does anybody know, is there any way to generate identical tables, but with different content?

I have heard about JS template engines (Mustache and others), and also AngularJS, but never used them before. Maybe I should use one of them, maybe not.

The code below should produce two identical tables, but with different content in their cells, as shown in jsFiddle

<!-- Here will be displayed the 1st table: -->
<object type="table-1x2">
  var foo = { <p>hello</p> }
  var bar = { <p>world</p> }
</object>

<!-- Here will be displayed the 2nd table: -->
<object type="table-1x2">
  var foo = { <p>hello</p> }
  var bar = {
    <div>hello, i'm a div!</div>
    <div>
      <p>hello, i'm a 1st paragraph!</p>
      <p>hello, i'm a 2nd paragraph!</p>
    </div>
  }
</object>



<!-- The section <objects></objects> should be located somewhere in the
     bottom of the document, below the <style></style> section -->

<objects>

  objectType="table-1x2" {
    <table>
      <tr>
        <td>{foo}</td>
        <td>{bar}</td>
      </tr>
    </table>
  }

</objects>

es6 gives us string interpolation which is a fancy way of saying a string with dynamic parts.

function getTable(foo, bar) {
  return `
    <table>
      <tr>
        <td>${foo}</td>
        <td>${bar}</td>
      </tr>
    </table>
  `
}

var foo1 = '<p>hello</p>'
var bar1 = '<p>world</p>'

var foo2 = '<p>hello</p>'
var bar2 = `
  <div>hello, i'm a div!</div>
  <div>
    <p>hello, i'm a 1st paragraph!</p>
    <p>hello, i'm a 2nd paragraph!</p>
  </div>
`

console.log(getTable(foo1, bar1))
console.log(getTable(foo2, bar2))

If you don’t want to use es6 just yet you’ll need to use a templating language like handlebars or use something simple like Underscores template function http://underscorejs.org/#template

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.