Load data from JSON file into Handlebars / MJML template - javascript

I've got an MJML template which compiles to HTML, and am wanting to load variables from a JSON file to the template. I'm new to HTML, JS & Handlebars so could be really off track here.
My MJML template, test.mjml, looks something like:
<mjml>
<mj-body>
<mj-raw><script type="text/javascript" src="handlebars-v4.7.3.js"></script></mj-raw>
<mj-raw><script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script></mj-raw>
<mj-section>
<mj-text><mj-raw>
<script id="test-template" type="text/x-handlebars-template">
<div>
<p>
Hello my name is {{name}}.
</p>
</div>
</script>
</mj-raw></mj-text>
</mj-column>
</mj-section>
I have a JSON file, data.json:
{
"name": "John",
"height": "175cm",
"occupation": "Teacher",
}
And a JS file, test.js:
$(document).ready(function() {
var template = $('#test-template').html();
var compiledTemplate = Handlebars.compile(template);
$.getJSON('data.json', function (data) {
var context = data;
}
});
var html = compiledTemplate(context);
$(document.body).append(html);
Does anyone know how to do this / what I'm doing wrong?
If I replace jQuery's getJSON method with an inline JSON, it works.

Related

Display multiple arrays in HandlebarsJS

I am having my first play with HandlebarsJS and I am looking to use multiple arrays within it. Is this possible?
I have setup a Codepen template but I am struggling to implement the data from 2 arrays and from an external URL. I have tried this with MustacheJS too, but I believe that only allows one array and no filtering- unlike Handlebars
Here is the external JSON
and the CodePen
<!-- REQUIRED - Display site name, url and title in top section. With product data below using the "other array-->
<script id="myTemplate" type="text/x-handlebars-template">
{{content}}
</script>
<div id="contentArea"></div>
<script>
var data = {"content": "Hello, World!"};
var source = $("#myTemplate").html();
var template = Handlebars.compile(source);
var html = template(data);
$("#contentArea").text(html);
</script>
Here is my first template attempt but failing to integrate the JSON array at the moment
It's possible using {{#each}} block helper. I also registered my own helper {{{s}}}, which simply returns it's argument JSON.stringify()'ied, so I can print those arrays. How you fetch them is another problem, I Copy & Paste them into the Javascript part of the code for simplicity. Also, here's JS fiddle:
var data = {"content": "Hello, World!", "multipleArrays": [
[
{
"productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/i0lfddlghaiwfqlvlqay/air-vortex-shoe-fmq6pS.jpg",
"producturl": "https://www.nike.com/gb/t/air-vortex-shoe-fmq6pS"
},
{
"productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/cmuof8adhfipkvd0f43r/air-max-95-shoe-XPTbV2mM.jpg",
"producturl": "https://www.nike.com/gb/t/air-max-95-shoe-XPTbV2mM"
}
],
[
{
"sitename": "Nike",
"sitetitle": "Nike. Just Do It.. Nike.com",
"siteurl": "https://www.nike.com/gb/en_gb/"
}
]
]};
Handlebars.registerHelper('s', function(arg) {
return JSON.stringify(arg);
})
var source = $("#myTemplate").html();
var template = Handlebars.compile(source);
var html = template(data);
$("#contentArea").html(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<!-- REQUIRED - Display site name, url and title in top section. With product data below using the "other array-->
<script id="myTemplate" type="text/x-handlebars-template">
<h1>Content: {{content}}</h1>
<hr>
<h2>Stringified multiple arrays:</h2>
{{{s multipleArrays}}}
<hr>
{{#each multipleArrays}}
<h2>Item {{#index}}</h2>
{{{s this}}}
<br>
<br>
{{/each}}
</script>
<div id="contentArea">
</div>

json data getting from url is not parsed in handlebars.js

I want to parse JSON data that I am getting from url in handlebars.
What I tried is I got the JSON data from the url.
I defined it into data object.
I want to know how can I parse the data using handlebars.js
I am new to handlebars.js
Is there any other way in which we can get without defining each property?
Because my JSON data is huge.
for eg.
reportData = {
inquiryId= data.data[0].inquiryId;
}
HTML code:
<script id="address-template" type="text/x-handlebars-template">
{{#with data}}
<p> My id is {{{inquiryId}}}</p>
{{/with}}
</script>
<div class="content-placeholder"></div>
JS code:
var reportData= {};
$(document).ready(function () {
$.ajax({
type:'GET',
url: reportURL,
success : function (data){
var inquiryId= data.data[0].inquiryId;
var theTemplateScript = $("#address-template").html();
console.log(theTemplateScript);
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
// Define our data object
reportData=data;
console.log(reportData);
// Pass our data to the template
var theCompiledHtml = theTemplate(reportData);
// Add the compiled html to the page
$('.content-placeholder').html(theCompiledHtml);
}
})
});
JSON:
{
"success":true,
"errors":{
},
"authenticated":true,
"program":1,
"data":[
{
"id":1,
"date":1505756267000,
"name":"AKKAYA, JORGE",
"productName":"Credit Profile",
"inquiryId":726608
}
]
}
My output is:
My id is
Can anyone help me out?
Thanks in advance.
In your Json, data contains array and in your html you are treating it like single object. So please use the below handlebar format to iterate over it.
{{#with abc}}
{{#each this}}
<p> My id is {{{inquiryId}}}</p>
{{/each}}
{{/with}}

Handlebars code inside of Ember Model field. How to evaluate?

Let's say I have some model with html field. This field contains some handlebars code. For example
<div class="foo">
{{model.title}}
</div>
The problem is when I'm trying to iterate over models and render html field, it doesn't evaluate handlebars code inside it.
{{#each models as |model|}}
{{{model.html}}}
{{/each}}
Here's an idea, create a Handlebars helper, that will compile handlebars.
With this sample, I believe you can build something that will suit your needs:
<script type="text/javascript" src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars.min-latest.js"></script>
<script>
var data = [{
"title": "Hey",
"subtitle": "I'm an inner handlebar template.",
"html": '<h1>{{title}}</h1><h2>{{subtitle}}</h2>'
}, {
"title": "Nice!",
"html": '<h1>{{title}}</h1>'
}];
/** Handlebar helper that will compile the content passed, with the data at index **/
Handlebars.registerHelper("compile", function(content, index) {
var template = Handlebars.compile(content);
return template(data[index]);
});
var content = '{{#each .}}\
{{{compile html #index}}}\
{{/each}}';
var template = Handlebars.compile(content);
document.body.innerHTML = template(data);
</script>
I never used ember, but I believe you can make it work easily ;)

Backbone: getting the html code of a view?

In order to write the HTML code of social icons (Twitter, Linkedin, etc) to a textarea so that the user can use that code elsewhere, I would like to get the HTML code of the view element, but I'm having some issues. To help illustrate this better, here is the code that creates the view:
define(function(require, exports, module) {
var _ = require('underscore');
var GridControlView = require('pb/views/grid-control');
var SocialiconsControlDialog = require('pb/views/socialicons-control-dialog');
var template = require('text!pb/templates/socialicons-grid-control.html');
var SocialiconsGridControlView = GridControlView.extend({
template: _.template(template)
,templateVars: {
partials: {
facebook: require('text!pb/templates/socialicons-grid-control-facebook.html')
,twitter: require('text!pb/templates/socialicons-grid-control-twitter.html')
,googleplus: require('text!pb/templates/socialicons-grid-control-googleplus.html')
,pinterest: require('text!pb/templates/socialicons-grid-control-pinterest.html')
,linkedin: require('text!pb/templates/socialicons-grid-control-linkedin.html')
}
}
,control_dialog: SocialiconsControlDialog
});
return SocialiconsGridControlView;
});
And, for example, the Linkedin template looks like this:
<script src="//platform.linkedin.com/in.js?<%- t.cache_buster %>" type="text/javascript">lang: en_US</script>
<script type="IN/Share" data-counter="<%- t.linkedin_option_countmode %>"></script>
What I would like to retrieve, is the parsed template code as text, something such as:
<script type="text/javascript" src="//platform.linkedin.com/in.js?0.4670609195438331">
<script data-counter="top" type="IN/Share+init">
But using something such as:
control_view.render().$el.innerHTML;, control_view.render().$el.html().text() or control_view.render().$el.html().replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, ""); doesn't return text; it returns the full HTML, and produces a Linkedin icon (when I just want the text to be written to a textarea).
Any thoughts?
Update **
I noticed that the code control_view.render().$el is working correctly on other places of the application, and returning HTML code, but for some reason in this view where I'm trying it doesn't. The code seems to break at:
$control = control_view.render().el;
and in the console I get an error which is:
TypeError: t is undefined - underscore-min.js (line 3)
Use the .outerHTML property of the $el.
var html = $('<script type="text/javascript" src="//platform.linkedin.com/in.js?0.4670609195438331">' +
'<script data-counter="top" type="IN/Share+init">');
var text = html[0].outerHTML;
$('textarea').val(text);
jsFiddle

How to load external html template?

Given HTML code such :
<!-- 2. Anchor -->
<div id="anchor">This div is the <b>#anchor</b>.</div>
<!-- 3. Template -->
<script id="tpl" type="text/template">
{{#people}}
<div><img src="{{photo}}"><b>{{family}} {{name}}</b> — {{title}}, {{place}} : {{introduction}}.</div>
{{/people}}
</script>
Given JS/Handlebars such as :
<!--4. Handlebars.js slingshot -->
//4a.function creation
var slingshot = function (url, tplId, anchor) {
$.getJSON(url, function(data) {
var template = $(tplId).html();
var stone = Handlebars.compile(template)(data);
$(anchor).append(stone);
});
}
slingshot('data.json', '#tpl', '#anchor'); // since url = 'data.json' , we can use both notations.
How to externalize the my 3. Template (#tpl) into a proper .txt text file (or other extension) ? How to load it back ? so I may use the same template into various .html webpages.
Full code : http://bl.ocks.org/hugolpz/8075193 / http://bl.ocks.org/hugolpz/raw/8075193/
Put the following template content into a file named test.handlebars
{{#people}}
<div><img src="{{photo}}">
<b>
{{family}} {{name}}
</b> — {{title}},
{{place}} : {{introduction}}.
</div>
{{/people}}
Write a function which will use the template as below
function getTemplate(name) {
if (Handlebars.templates === undefined || Handlebars.templates[name] === undefined) {
$.ajax({
url : name + ".handlebars",
success : function(data) {
if (Handlebars.templates === undefined) {
Handlebars.templates = {};
}
Handlebars.templates[name] = Handlebars.compile(data);
},
async : false
});
}
return Handlebars.templates[name];
}
In the main program you can write the below statement to insert the template contents into div with id="anchor", as shown below
var Template = getTemplate("test")
this.$("#anchor).append(Template(data));
where data is the contents of a json file or some db query output which will give you the values meant for the following attributes in json format
people, twitter, name, family, photo, title, place, introduction
I'm assuming you have already compiled your template. So you can use the technique I have described in Bootstrapping Multiple Instances of an HandlebarsJS Template Into a Page.
Hook and libs
Place this in your index.html:
<div class="hook" data-json="data/whatever.json"></div>
and the JavaScript libs
<!-- Helper to inject data-set in templates instance -->
<script src="scripts/template-loader.js"></script>
<!-- Get the (compiled) template -->
<script src="scripts/myTemplate.hbs.js"></script>
template-loader.js helper
$(function(){
'use strict';
var compiledTemplate = myApp.Templates['app/templates/myTemplate.hbs'];
$('.hook').each(function(i, h){ # h = current hook
var url = $(h).data('json'); # data-set's url
$.getJSON(url).then(function (json) { # fetch data-set
var tpl = compiledTemplate( json ); # inject data into template
$(h).html(tpl); # inflate template in page
});
});
});
Please read the complete article for further details.

Categories

Resources