Javascript templating

Published: Tuesday, Apr 25, 2017 Last modified: Thursday, Nov 14, 2024

Inspired by Templating languages: The hidden costs - Fun Fun Function

Consider the primitive way:

https://codesandbox.io/s/nrJJRDjJW

import React, { DOM } from 'react';
import { render } from 'react-dom';

const { div, li, p, ul } = DOM;

function renderPricesContainer(items) {
  return div({ className: 'list-container'},
	items.length
		? ul({}, items.map(item => li({}, item.price)))
		: p({}, 'No items found')
	);
}

var i = [{ price: 12.12}, { price: 0.01 }]
const App = () => (
  <div>
	{renderPricesContainer(i)}
  </div>
);

render(<App />, document.getElementById('root'));

JSX

https://codesandbox.io/s/NkqxXlvXD

import React from 'react';
import { render } from 'react-dom';

const App = ({ items }) => (
  <div className="list-container">
	{items.length > 0
	  ? <ul>{items.map(item => <li>{item.price}</li>)}</ul>
	  : <p>No items found</p>}
  </div>
);

render(
  <App items={[{ price: 12.12 }, { price: 0.01 }]} />,
  document.getElementById('root'),
);

Alternative light weight templating: https://gist.github.com/brigand/94c09476676a70e78e33ca84f0cc8ad3