Both mustache and handlebars are awesome. I like them both for their individual simplicity and excellence. Mustache because it's a one template works in lots of places and handlebars because it provides just a few more features.
The challenge I have is that they seem to have been implemented to output HTML or some other document structure where the tags are in pairs and there are no separators.
To further clarify, if you have an array of items that would be output in a list then this works well:
<ul>
{{#each items}}
<li>{{name}}</li>
{{/each}}
</ul>
This works great. But if you want to output something JSON-like:
[
{{#each items}}
{ name:{{name}} }
{{/each}}
]
This does not work because JSON requires that there be commas separating items in a list. And you cannot put a comma after the innermost '}' because that would cause an error too.
There are several posts/recommendations where people have requested that an optional separator attribute be added to the #each or adding a #join. One committer said that it should be implemented as a plug-in because the core needs to be simple.
The politics aside. Being able to format a javascript object as a JSON string seems well suited for templates.
**One final idea. There may actually be a better Javascript Idiom for reformating a JavaScript object. I suppose that would also be interesting to consider.
PS: the one reason I like the template is because it becomes self documenting.
UPDATE:
#Kevin over at the handlebarsjs team was able to create a "Helper" function that implemented the feature I was missing. It's not like to make it into the core any time soon but that code worked:
[
{{#join items sep=','}}
{ name:{{name}} }
{{/join}}
]
Related
I am using html-pdf for pdf creation on my project. i can generate all the details into the pdf. but the thing is i can not be able to create List of items in array in html(which will be used for pdf conversion).
Since i cannot use javascript to get the array of items, i am unable to get it. if there is a tweak to use javascript in html template,please post it here. Since the array of items is known, i can use it easily.
Suppose if the array length is 3 . i can use like array[0].name ,array[1].name, array[2].name but here i don't know the length of the array which consists of how many items. Can anyone please help me here to generate the table of items which is generating dynamically.
You cannot use Javascript in template, but you can use Javascript on it.
The idea is to make a parser which will :
read your template
replace a keywork (for example : <customTable arrayName="myCustomArray" fields="['name']" />) with a generated HTML array in Node.js.
use this template with html-parser.
I write an example of parser in VanillaJS here : https://jsfiddle.net/rbuuzcre/5/
I stumbled upon this code:
<a href="#" class="text1"{text2}>...</a>
What does the {text2} do? Later on, this HTML is replaced with:
<a href="#" class="text1" {text2} style>...</a>
Is there a way I can retrieve the text2 value with jQuery?
In some cases that code is input in, so scripts can actually easily identify a the line. Or in some cases can be an indicator for a database to retrieve and store data once it has been pulled.
Or it could be invalid markup, doubtful if the person knows what they are doing.
But without any other information or variables it is hard to say. But the most common is access for scripts within Php, Javascript, and even C#. Cause they can parse the HTML document and manipulate it. If those braces are used, and it is incorrectly it will cause a parse error.
Hopefully that sort of clarifies it.
Update:
Yes, jQuery can find it. It is a form of Javascript. You could implement something such as:
$(function() {
var foundString = $('*:contains("{text1}")');
});
There is a vast amount of data that addresses this for more detail.
It does nothing in HTML. It's actually invalid markup. Looks like maybe you have a template system that finds and replaces that before it gets rendered to the browser.
I know that in jinja2, a python templating system, brackets contain commands to the template engine, either as:
Hello, {{varName}}
or:
<ol>
{%for l in varList%}
<li>{{l}}</li>
{%endfor%}
</ol>
That's in jinja, but jinja has similar syntax to django templates, and many other template engines probably copy django's syntax also.
its used in angular js and are called expressions {{expression}}
AngularJS is a JavaScript framework. It can be added to an HTML page with a tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.
Is there a way to nicely format/style JSON code in Github Wiki (i.e Markdown preferred)?
Something like this with few colors (or bold) and correct indentation:
http://www.freeformatter.com/json-formatter.html#ad-output
Some color-syntaxing enrichment can be applied with the following blockcode syntax
```json
Here goes your json object definition
```
Note: This won't prettify the json representation. To do so, one can previously rely on an external service such as jsbeautifier.org and paste the prettified result in the wiki.
```javascript
{ "some": "json" }
```
I tried using json but didn't like the way it looked. javascript looks a bit more pleasing to my eye.
2019 Github Solution
```yaml
{
"this-json": "looks awesome..."
}
Result
If you want to have keys a different colour to the values, set your language as yaml
#Ankanna's answer gave me the idea of going through github's supported language list and yaml was my best find. (No other language had keys a different colour to values on github).
Also you can use comments in yaml with //
I encountered the same problem. So, I tried representing the JSON in different Language syntax formats.But all time favorites are Perl, js, python, & elixir.
This is how it looks.
The following screenshots are from the Gitlab in a markdown file.
This may vary based on the colors using for syntax in MARKDOWN files.
I'm looking to build a system that styles the search results from DocumentCloud (and allows me to link to a given document).
I know I can query DocumentCloud and return JSON results using a search string like this:
https://www.documentcloud.org/api/search.json?q=obama
I don't know how to:
Grab the output of the search and put it on my own page
Style the data once I have it on my page
I'd just like to know how to get started with this, I'm experienced with HTML and CSS but I've never worked with JSON before.
There's more info here but I just don't know where to get started: https://www.documentcloud.org/help/api
It sounds like you're not so familiar with JavaScript, correct? JSON stands for JavaScript Ojbect Notation, so to work with it, you'll have to dive in a bit. I strongly recommend looking into using a JavaScript framework/library, namely jQuery to handle the heavy lifting. (There are other worthy libraries, but jQuery is by far the most popular, and is very friendly, using CSS-like selectors to manipulate the document object model).
check this jQuery tutorial: How jQuery Works
Here's a primer on using jQuery's jsonp to fetch remote rsults and using them in a page: http://www.ibm.com/developerworks/library/wa-aj-jsonp1/
You might end up with code in a javascript file, or a script tag (following a link to the jQuery library) that looks like this:
$(document).ready(function () {
$.getJSON('https://www.documentcloud.org/api/search.json?q=obama&callback=?', null, function (results) {
// this would append whatever the json returns for 'total'
// inside an element on your page with an id of 'resultsCount':
$('#restulsCount').append(data.total);
});
});
As a result, extra text & markup can be added to elements you already have on your page in whatever form/position you need it, and regular CSS rules from any style block or CSS file linked on your page will apply to them.
Good luck.
I have HTML content stored in a variable. How do I extract data that is found between a set of common tags in the page? For example, I am interested in the data (represented by DATA kept between a set of tags which one line after the other:
...
<td class="jumlah">*DATA_1*</td>
<td class="ud">*DATA_2*</td>
...
And then I would like to store a mapping DATA_2 => DATA_1 in a hash
Since it is HTML I think this could work for you?
https://metacpan.org/pod/XML::XPath
XPath is the way.
Since it's HTML, you probably want the XPath module made for working with HTML, HTML::TreeBuilder::XPath.
First you'll need to parse your string using the HTML::TreeBuilder methods. Assuming your webpage's content is in a variable named $content, do it like this:
my $tree = HTML::TreeBuilder->new;
$tree->parse_file($file_name);
Now you can use XPath expressions to get iterators over the nodes you care about. This first expression gets all td nodes that are in a tr in a table in the body in the html element:
my $tdNodes = $tree->findnodes('/html/body/table/tr/td');
Finally you can just iterate over all the nodes in a loop to find what you want:
foreach my $node ($tdNodes->get_nodelist) {
my $data = $node->findvalue('.'); // the content of the node
print "$data\n";
}
See the HTML::TreeBuilder documentation for more on its methods and the NodeSet documentation for how to use the NodeSet result object. w3schools has a passable XPath tutorial here.
With all this, you should be able to do pretty robust HTML parsing to grab out any element you want. You can even specify classes, ids, and more in your XPath queries to be really specific about which nodes you want. In my opinion, parsing HTML using this modified XPath library is a lot faster and more maintainable than dealing with a bunch of one-off regexes.
Use HTML parsing modules as described in answers to this Q - HTML::TreeBuilder or HTML::Parser.
Purely theoretically you could try doing this using Regular Expressions to do this but as noted in the linked question's answers and countless other times on SO, parsing HTML with RegEx is a Bad Idea with capital letters - too easy to get wrong, too hard to get well, and impossible to get 100% right since HTML is not a regular language.
You might try this module: HTML::TreeBuilder::XPath. The doc says:
This module adds typical XPath methods to HTML::TreeBuilder, to make it easy to query a document.