Creating templates dynamically from JSON in AngularJS - json

I am parsing or reading a JSON file in my AngularApp. I want to create one template for each object inside the JSON file, and then load it with "previous" and "next" in my app.
So i have a JSON file, for example:
{
"name": "test",
"objects":[
{"one": "text here", "id" : "1" },
{"two": "and text there", "id" : "2" }
]
}
So i want to create a template called "template1" and "template2".
I am starting with Angular, so i don't need a whole workaround, just where do i have to dig deeper?
I created a controller for my app
I've then created a jsonService which injectes the controller
Now i have the JSON data
But what then? Do i have to create Directives? And how to load them into my main-page? With data-ng-view?

See this example which will give you an example of how you can iterate over json and render to html:
https://github.com/eu81273/angular.treeview/blob/master/angular.treeview.js

Thanks #Nikos for this possibility. I found a much simpler soultion:
I hard coded a ng-switch on="option" and then a ng-switch-when="optionN" in each div, so i can dynamically adjust one template to fit all options.

Related

unable to put json file in an ordered HTML that looks prettier

I am trying to put my contents of JSON files in a prettier HTML format with tables and rows and probably colors too but have no idea how can I do that. Can anyone please assist. Below are two JSON files I am trying to put it in HTML file
'''
{"CorrelationId": "awsnightlyendtoend_zone08_20190828T2319", "ValidationType": "validate_adwactivityfact", "Success": false, "OutputPath": ["s3://zone08-data-validation/awsnightlyendtoend_zone08_20190828T2319/validate_adwactivityfact/requires-replay.csv", "s3://zone08-data-validation/awsnightlyendtoend_zone08_20190828T2319/validate_adwactivityfact/require-investigation.csv"], "ValidationDetail": "Comparison Failed: matched=146455, missing=6, mismatched=0, percent success=99.9918066925666%"}
{"CorrelationId": "awsnightlyendtoend_zone50_20190828T2303", "ValidationType": "validate_adwactivityfact", "Success": false, "OutputPath": ["s3://zone50-data-validation/awsnightlyendtoend_zone50_20190828T2303/validate_adwactivityfact/requires-replay.csv", "s3://zone50-data-validation/awsnightlyendtoend_zone50_20190828T2303/validate_adwactivityfact/require-investigation.csv"], "ValidationDetail": "Comparison Failed: matched=145541, missing=24, mismatched=0, percent success=99.96702504036%"}
'''
If you're only going to do it once, you can use an online json to html converter (like this one: http://convertjson.com/json-to-html-table.htm
If not, you'll have to use some javascript to convert parse the json and display as html.
(Probably just jQuery may do the trick)

assemble.io partial pass data to nested partials

I am using assemble.io and I would want to modularize everyhing using the "atomic design" principles.
Let's say that I start with a couple of single atoms
atomic partial "title" (a-h2-title.html)
<h2 class="{{additionalclasses}}">{{title}}</h2>
atomic partial "info text" (a-info-text.html)
<div class="info {{additionalclasses}}">
{{{text}}}
</div>
As far as I have understood, if I want to use "instances" of these generic components with some data I can define them in a json file like in this example:
info-text-example1.html
{{>a-info-text info-text-example1}}
info-text-example1.json
{
"text":"<p>some text</p>",
"additionalclasses"="info--modified"
}
Ok, now my problem is when I want to define for example a molecule:
m-text-and-title.html
<div class="box {{additionalclasses}}">
{{>a-h2-title}}
{{>a-info-text}}
</div>
Now, if I want an "instance" for this element
text-and-title-example1.html
{{>m-text-and-title ???}}
How can I define all the data for the object itself (additionalclasses) and for the child objects?
I hope I have made myself clear
I've already seen this article here but I am not able to adapt it to my case
Thank you for your answer
You will still have to create the data structure in a way that you need it, then in the pages or partials pass the values to the sub-partials. So in this case, I think you can use the following pattern:
text-and-title-example1.html
{{>m-text-and-title text-and-title-example1}}
text-and-title-example1.json
{
"additionalclasses": "text-and-title--modified",
"title-example": {
"title": "some title",
"additionalclasses": "title-modified"
},
"text-example": {
"text": "<p>some text</p>",
"additionalclasses": "info--modified"
}
}
Then update the molecule to be this:
<div class="box {{additionalclasses}}">
{{>a-h2-title title-example}}
{{>a-info-text text-example}}
</div>
Now this works the same way as your initial example. You have a data object with properties that you've specified, then you pass those properties into the partials that will use them. The "atoms" have generic, reusable properties already and you can change your "molecule" to do the same... like change title-example to title and text-example to text, but keep them as objects that are passed down to the "atoms".

How would you embed atomic partials into a template data object

I'm using handlebars and assemble with yeoman and gulp.
I want to have some globalized partials that are able to be nested or injected into another partial by calling it within the context of a data object.
A simple example of that would be having a list of links that I could reference inside content throughout the site. The reason behind this, is the need for consistency. If for example, if I have a link within text on a page that I reference a 15 times throughout an entire website, but then realize I need to add a trade mark or modify the text, I want to update it once, not 15 times.
This is an example of what I want to do. Define global data inside a json file:
links.json
{
"apple": {
"linktext": "apple",
"target": "_blank",
"href": "http://www.apple.com"
},
"blog-article-foo-bar": {
"linktext": "foo bar",
"href": "http://www.foobar.com"
},
"dell": {
"linktext": "dell",
"target": "_parent",
"href": "http://www.dell.com"
}
}
Generate a partial from that content using a simple or complex template:
links.hbs
<a href="{{href}}" {{#if target}}target="{{target}}"{{/target}}>{{linktext}}</a>
And be able to embed that partial into another one by referencing it some how. This didn't work, but I've been reading about custom helpers, but can't figure out how I would intercept the partial and bind it into the other partial.
text.json
{
"text": "If you need a computer, go to {{> link link.apple}}."
}
text.hbs
<p>
{{text}}
</p>
compiled.html
<p>
If you need a computer, go to apple.
</p>
If you have suggestions or examples that might help me understand how to achieve this, I'd really appreciate the support. Thanks in advance.
There is some information about Handlebars helpers in their docs but not that much.
Since you're trying to use handlebars syntax in the value of a property on the context (e.g. text), handlebars won't render the value since it's already rendering the template. You can create your own helper that can render the value like this:
Handlebars.registerHelper('render', function(template, options) {
// first compile the template
const fn = Handlebars.compile(template);
// render the compiled template passing the current context (this) to
// ensure the same context is use
const str = fn(this);
// SafeString is used to allow HTML to be returned without escaping it
return new Handlebars.SafeString(str);
});
Then you would use the helper in your templates like this:
{{render text}}
Thanks for the example #doowb, your code did work but not for what I was trying to do. I really wanted something more complicated but I simplified my question not knowing it would be an issue. The code you provided worked (I think after a slight tweak) for a simple render of a template, but my templates use helpers such as #each and #if which caused the issue. Where the helpers were in my template, I ended up getting async placeholders. For example: <a $ASYNC$1$3...> I later learned this has to do with how partials are rendered. Understanding that lead me to subexpressions and the below solution.
Keeping my example above with some modifications, this is how I was able to merge partials.
First, I simplified the placeholder in text.json to basically a unique ID, instead of trying to render the partial there.
On the hbs template that I'm rendering to, such as a page or whatever, I included the insert helper with 3 arguments. The first two are subexpressions, each return a flattened partials as strings. The key here is that subexpressions process and return a result before finishing the current process with the helper. So two flattened templates are then sent to the helper along with the placeholder to search for.
The helper uses the third argument in a regex pattern. It searches the second argument (flattened parent template) for this pattern. When found, it replaces each instance of the pattern with the first argument (yes its a global fine replace).
So, the flattened child string gets inserted into parent each time placeholder is found.
First argument
(partial "link" link.apple)
Returns
'apple'
Second argument
(partial "text" text.text-example)
Returns
'<p class="text font--variant">If you need a computer, go to {{linkToApple}}.</p>'
Third argument
'linkToApple'
text.json
{
"text-example": {
"elm": "quote",
"classes": [
"text",
"font--variant"
],
"text": "If you need a computer, go to {{linkToApple}}."
}
}
text.hbs
<{{elm}} class="{{#eachIndex classes}}{{#isnt index 0}} {{/isnt}}{{item}}{{/eachIndex}}">{{text}}</{{elm}}>
compile.hbs
{{insert (partial "link" link.apple) (partial "text" text) 'linkToApple' }}
compile.html
<p class="text font--variant">If you need a computer, go to apple.</p>
gulpfile.js
app.helper('insert', function(child, parent, name) {
const merged = parent.replace(new RegExp('\{\{(?:\\s+)?(' + name + ')(?:\\s+)?\}\}', 'g'), child);
const html = new handlebars.SafeString(merged);
return html;
});
Hope this helps someone else. I know this can use improvements, I'll try to update it when I get back to cleaning up my gulp file.

Using the Wordpress JSON API to get custom field (image)

I'm trying to dynamically load images from a certain post type. I've used the Advanced Custom Fields plugin to attach an image field to my post. I'm currently using this code:
$.getJSON('/?json=get_recent_posts&post_type=slides-verhuur&custom_fields=image', {}, function(data){
console.log(data);
});
However when I run the code, the result JSON I get contains a "custom field" attribute, which have an "image" attribute, but this only contains the value of "80", which is the ID of the image. Is there a way to get the image url instead?
You need to set Return Value as "Image URL" instead of "Image ID" Under Custom Fields group a image field as per image shown below.
$post_response->data['CFS'] = CFS()->get(false, $page->ID, array('format' => 'api'));
use 'api' instead of 'raw'

Best practices for Storing JSON in DOM

I want to render some json data using HTML template.
I haven't started implementing anything yet, but I would like to be able to "set" values of data from json to html element which contains template for one record, or to render some collection of items using some argument which is template html for each item, but also to be able to get JSON object back in same format as source JSON which was used to render item (I want my initial JSON to contain some more information about behavior of record row, without the need to make ajax request to check if user can or can't do something with this record, and not all of this info is visible in template).
I know that I could make hidden form with an input element for each property of object to store, and mapper function to/from JSON, but it sounds like overkill to me, and I don't like that, I want some lighter "envelope".
I was wondering is there some JS library that can "serialize" and "deserialize" JSON objects into html so I can store it somewhere in DOM (i.e. in element which contains display for data, but I want to be able to store additional attributes which don't have to be shown as form elements)?
UPDATE As first answer suggested storing JSON in global variable, I also have thought about that, and my "best" mental solution was to make JavaScript module (or jQuery plugin) which would do "mapping" of JSON to html, and if not possible to store values in html then it can store them in internal variable, so when I want to "get" data from html element it can pull it from its local copy. I want to know is there better way for this? If there is some library that stores this info in variable, but does real-time "binding" of that data with html, I would be very happy with that.
UPDATE 2 This is now done using http://knockoutjs.com/, no need to keep json in DOM anymore, knockout does the JSON<=>HTML mapping automatically
Why not store it as nature intended: as a javascript object? The DOM is a horrible place.
That said, jQuery has the data method that allows just this.
So you want to keep a reference to the JSON data that created your DOMFragment from a template?
Let's say you have a template function that takes a template and data and returns a DOM node.
var node = template(tmpl, json);
node.dataset.origJson = json;
node.dataset.templateName = tmpl.name;
You can store the original json on the dataset of a node. You may need a dataset shim though.
There is also no way to "map" JSON to HTML without using a template engine. Even then you would have to store the template name in the json data (as meta data) and that feels ugly to me.
I have done this in the past as well in a couple of different ways.
The $('selector').data idea is probably one of the most useful techniques. I like this way of storing data because I can store the data in a logical, intuitive and orderly fashion.
Let's say you have an ajax call that retrieves 3 articles on page load. The articles may contain data relating to the headline, the date/time, the source etc. Let's further assume you want to show the headlines and when a headline is clicked you want to show the full article and its details.
To illustrate the concept a bit let's say we retrieve json looking something like:
{
articles: [
{
headline: 'headline 1 text',
article: 'article 1 text ...',
source: 'source of the article, where it came from',
date: 'date of the article'
},
{
headline: 'headline 2 text',
article: 'article 2 text ...',
source: 'source of the article, where it came from',
date: 'date of the article'
},
{
headline: 'headline 3 text',
article: 'article 3 text ...',
source: 'source of the article, where it came from',
date: 'date of the article'
}
]
}
From an ajax call like this . . .
$.ajax({
url: "news/getArticles",
data: { count: 3, filter: "popular" },
success: function(data){
// check for successful data call
if(data.success) {
// iterate the retrieved data
for(var i = 0; i < data.articles.length; i++) {
var article = data.articles[i];
// create the headline link with the text on the headline
var $headline = $('<a class="headline">' + article.headline + '</a>');
// assign the data for this article's headline to the `data` property
// of the new headline link
$headline.data.article = article;
// add a click event to the headline link
$headline.click(function() {
var article = $(this).data.article;
// do something with this article data
});
// add the headline to the page
$('#headlines').append($headline);
}
} else {
console.error('getHeadlines failed: ', data);
}
}
});
The idea being we can store associated data to a dom element and access/manipulate/delete that data at a later time when needed. This cuts down on possible additional data calls and effectively caches data to a specific dom element.
anytime after the headline link is added to the document the data can be accessed through a jquery selector. To access the article data for the first headline:
$('#headlines .headline:first()').data.article.headline
$('#headlines .headline:first()').data.article.article
$('#headlines .headline:first()').data.article.source
$('#headlines .headline:first()').data.article.date
Accessing your data through a selector and jquery object is sorta neat.
I don't think there are any libraries that store json in dom.
You could render the html using the data from json and keep a copy of that json variable as a global variable in javascript.