JSFiddle - React, Tailwind, and code Playground
by Adam Kinnucane
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.js"></script>
<div class="result"></div>
<script id="content-stream" type="text/html">
{{#each Tags}}
{{#compare tag "eq" "In Stock"}}
<div class="cs-sold-banner"></div>
<div class="cs-sold-text"><p>sold</p></div>
{{/compare}}
{{/each}}
{{#each Tags}}
{{#matches tag "equals" "In Stock" "and" property "equals" "Condition"}}
<div class="cs-sold-banner"></div>
<div class="cs-sold-text"><p>not sold</p></div>
{{/compare}}
{{/each}}
</script>
JavaScript
var data = {
"Tags": [{
"tag": "In Stock",
"property": "Availability"
}, {
"tag": "Mixers / Blenders",
"property": "Navigation"
}, {
"tag": "New",
"property": "Condition"
}, {
"tag": "Ribbon Blender",
"property": "Machine Type"
}, {
"tag": "Stainless Steel",
"property": "Construction"
}]
}
Handlebars.registerHelper('hasTag', function( value1, value2, options) {
var match;
switch ( comparator ) {
case "==":
match = ( value1 == value2 );
break;
case "===":
match = ( value1 === value2 );
break;
case "!=":
match = ( value1 != value2 );
break;
case ">":
match = ( value1 > value2 );
break;
case "<":
match = ( value1 < value2 );
break;
case ">=":
match = ( value1 >= value2 );
break;
case "<=":
match = ( value1 <= value2 );
break;
case ">=":
match = ( value1 >= value2 );
break;
case "eq": // not a js operator
match = ( value1 == value2 );
break;
case "ne": // not a js operator
match = ( value1 != value2 );
break;
case "=~": // use js regex matching, with case insensitive on
case "regex":
case "match":
var re = new RegExp( value2, 'i' );
var m = re.exec( value1 );
match = ( m && ( m.length > 0 ) );
break;
default:
match = false;
console.error("Handlebars Helper - Compare was not given a supported operator");
}
if ( match ) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Handlebars.registerHelper('matches', function( value1, comparator1 , value2, comparator2 , value3, comparator3, value4, options) {
});
function render() {
var source = $("#content-stream").html();
var template = Handlebars.compile(source);
$('.result').html(template(data));
}
render();