You are now ready to add the horizontal menu and query for the categories list:
- Add the HTML in bold to index.html:
<div class="app-main">
<div>
<ul id="menu"></ul>
</div>
</div>
- Create a file named app.js, then implement a categories query and execute it when the app loads:
const templatesCache = {};
function render(props) {
return function(tok, i) { return (i % 2) ? props[tok] : tok; };
}
// a basic templating approach that uses regex for formatting specified props into the relevant placeholders in the template
function renderTemplate(templateName, props) {
let template = templatesCache[templateName];
if (!template) {
// reserve templates in cache for future quicker access
template = $(`script[data-template="${templateName}"]`).text()
.split(/${(.+?)}/g);
templatesCache[templateName] = template;
}
// map every placeholder to a matching specified prop and build the finalized HTML
return template.map(render(props)).join('');
}
function loadCategories(callback) {
const menu = $('#menu');
window.api.getCategories(items => {
items[0].className = 'menu-selected';
menu.append(items.map(item => renderTemplate('menu-item', item)));
if (callback) callback();
});
}
function setupAppMenu() {
$('#menu').menu({items: "li"});
$('#menu > li').click(e => {
$('#menu > li').removeClass('menu-selected');
$(e.currentTarget).toggleClass('menu-selected');
});
}
function bootstrapApp() {
loadCategories(setupAppMenu);
}
$(bootstrapApp);
- Add references to the relevant scripts in index.html:
...
<script src="api.js"></script>
<script src="app.js"></script>
</body>
You can now view the page and see the menu and populated categories in action, it should look similar to this -