I am in beginning of a web project and I want to read my web site stings such as labels, title of pages, placeholder and ... from a json file. i think this approach may help me to increase my speed in changes and create a multi language web site.
is there any jquery library for doing this? and if ther is not how can i do this work by jquery?
You can make mustache templates and populate them with data using handlebars.js:
http://handlebarsjs.com/
Mustache templates use curly braces as placeholders and handlebars uses the json format to hold the data. It could look something like this (though not a full working example):
HTML:
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
Javascript:
var context = {title: "My New Post", body: "This is my first post!"};
var html = template(context);
Result:
<div class="entry">
<h1>My New Post</h1>
<div class="body">
This is my first post!
</div>
</div>
Here is a working example: https://jsfiddle.net/k4u64exL/
What you're searching for is a Javascript/jQuery Template Engine - there are lot of them (start e.g. with http://www.sitepoint.com/10-javascript-jquery-templates-engines/ ).
If you want to write your own template engine try the following:
1) Fetch JSON-Data with Ajax
2) Fetch Template with Ajax
3) Apply variables from JSON-File to Template File (simple replace)
4) Append the result to the current page.
Related
I would like to display a list of hotels in HTML using data from this Google sheet:
https://docs.google.com/spreadsheets/d/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/
I am using JSON and jQuery, and would like to use jQuery to loop over all of the rows, displaying them in HTML format.
So far I have managed to display some content using JSON but I am unsure how to proceed with displaying all of the rows:
Codepen: http://codepen.io/aljohnstone/pen/adobow
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json',function(data){
//remove http:// for a text
var url = data.feed.entry[0]['gsx$url']['$t'];
var shortUrl = url.replace('http://', '');
//give id's google sheet values
$('#bandb').text(data.feed.entry[0]['gsx$name']['$t'])
$('#description').text(data.feed.entry[0]['gsx$description']['$t'])
$('#image').attr("src", (data.feed.entry[0]['gsx$image']['$t']));
$('#link').text(shortUrl).attr("href", (data.feed.entry[0]['gsx$url']['$t']));
});
Use jquery foreach
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json',function(data){
$.each(data.feed.entry,function(i,v){
var url = v.gsx$url.$t;
var shortUrl = url.replace('http://', '');
var data = $('<div class="listing">').append('<img src="'+v.gsx$image.$t+'" id="image"/><h4 id="bandb">'+v.gsx$name.$t+'</h4><p id="description">'+v.gsx$description.$t+'</p>'+shortUrl+'');
$('body').append(data);
});
});
http://codepen.io/anon/pen/mVbypE?editors=001
I'd recommend using a front-end templating framework, such as mustache.js. There are a lot of options in this area. What you will typically do in a templating framework is define an HTML template that uses placeholders for your data. Then, in your javascript, you'll pass the data object into the templates. Here's how it might look in mustache:
Template
<script id="listing-template" type="text/html">
<div class="listing">
<img class="image" src="{{gsx$image.$t}}"/>
<h4 class="bandb">{{gsx$name.$t}}</h4>
<a class="link" href="{{gsx$url.$t}}">{{gsx$url.$t}}</a>
<p class="description">{{gsx$description.$t}}</p>
</div>
</script>
JavaScript
<script>
$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json',function(data){
// loop through the entry object and append new templated elements to body element
$("body").mustache("listing-template",data.feed.entry);
});
</script>
I left out the initialization details for the mustache framework, but this is the general idea.
I need write static web page with simple data.
In form i have data from user and in tag
<div id="prog"> my output
How using Opal writing string into specyfic place?
<div id="prog">
</div><script type="text/javascript">
<div id="prog">
</div>
</script>
pp = document.getElementById("prog").innerHTML = Opal.main()
</script>
Ok, so based on your sample code, you just need to make Opal.main() return a string
def main
# logic
return str
end
But I think that what you really want is use opal-jquery or opal-browser, I don't have much experience with the later, so here's a simple example of opal-jquery (of what I understood you were asking)
Document.ready?
Element["form"].on(:submit) do
Element["#prog].text = Element["#input-id"].value
end
end
How would I render a page and go to a specific id?
Right now I have a following function with this code:
#cherrypy.expose
#require
def page():
tmpl = lookup.get_template('page.html')
return tmpl.render()
However, now the page.html does have several subpages, which I can access through URL like mydomain.com/page#someid.
Is there a way to render a template to go directly to the id?
I think that you are mixing the ideas, the # part of the URL is the client duty to focus in the specific element id. Nevertheless, I suppose that you want to do that to dynamically embed chunks of a particular part of the page trough javascript, I can think on two possibilities:
One, compose the full page template with the different ids from different sub-templates, this is easy if you are using a template module, like mako, and make a cherrypy handler to return the indivudual parts, this is of course supposing that you are in control of the content of the page and the ids are not dynamic (generated from a db or something) and the main site is a bunch of includes.
#cherrypy.expose
def page_part(section):
tpl_name = 'page_%s.html' % section
# validate that the template exists, then:
tmpl = lookup.get_template(tpl_name)
return tmpl.render()
Mako templates:
page.html:
<html>
<body>
<div id="main">
This is the main content of the site!
</div>
<h4>Sections</h4>
<div id="section_1">
<%include file="page_section1.html" />
</div>
<div id="section_2">
<%include file="page_section2.html" />
</div>
</body>
</html>
page_section1.html:
<p> Content of section 1</p>
page_section2.html:
<p> Content of section 2</p>
Or two, use jQuery selectors or something similar to request the page once and make the sub-selects in the returned html.
$.get('/page.html',
function(data){
$('#this_page_id').html($('#sect_in_other_page', $(data)).html());
});
I'm looking for a very basic example of using Javascript to parse a JSON file and output an html file or populate an html file. All the examples I've located so far have code snippets and I don't have the background to fill in the blanks between.
Thank you for any fiddles (which would be awesome), links, and smart a*s comments.
Templating example
I would suggest on of templating tools for example PURE...
The purpose of such a tool is separation of logic and representation.
For example, generating a list from JSON data using mentioned tool would look like this:
JSON data file
{'who':'BeeBole!'}
HTML file
<html>
<head>
<title>PURE Unobtrusive Rendering Engine</title>
<script src="../libs/jquery.js"></script>
<script src="../libs/pure.js"></script>
</head>
<body>
<!-- the HTML template -->
Hello <a class="who" href="#"></a>
<script>
// the JSON data we want to render
$.getJSON('yourJSONdataFile.json', function(data) {
// run the rendering
$('a').autoRender(data);
// PURE tries to match class with the JSON property and replace the node value with the value of the JSON property
});
</script>
</body>
</html>
This is most basic approach appropriate if you have simple JSON data (see working JSFiddle example there).. Get Started guide will walk you trough another example if basic approach isn't suitable. For more advanced features take look at the documentation.
Alternatives
There was no particular reason that PURE has been used in above example. There are many other alternatives out there:
EJS
Mustache
Tempo
...
...or you can do it manually as explained there.
You can use a microtemplating library, like Mustache, to parse incoming JSON objects into HTML snippets using {{ key }} template syntax. If your object looks like:
var myObj = {
name: 'Joe Smith',
age: 25,
features: {
hairColor: 'red',
eyeColor: 'blue'
}
};
Using Mustache, you can render it into HTML easily using {{#}} and {{/}} to traverse nested objects:
Mustache.render('Hello, my name is {{name}} and I am {{age}} years old. {{#features}} I have {{hairColor}} hair and {{eyeColor}} eyes.{{/features}}', myObj);
which outputs:
Hello, my name is Joe Smith and I am 25 years old. I have red hair and blue eyes.
EDIT: more germane application - dynamically generate a control panel using a template with nested lists of objects. Here's my template and object (HTML broken into a list and joined for clarity):
var panel = [
'<div id="cpanel">',
'{{#cpanel}}',
'<div class="panel_section">',
'<h1 class="cpanel">{{name}}</h1>',
'<p>',
'{{#content}}',
'<button id="{{id}}">{{id}}</button>',
'{{/content}}',
'</p>',
'</div>',
'{{/cpanel}}',
'</div>',
].join('\n');
var panelObj = {
cpanel: [
{
name: 'playback',
content: [
{id: 'play'},
{id: 'pause'},
{id: 'stop'}
]
}, {
name: 'zoom',
content: [
{id: 'zoomIn'},
{id: 'zoomOut'}
]
}]
};
Then you render with Mustache:
Mustache.render(panel, panelObj);
which outputs:
<div id="cpanel">
<div class="panel_section">
<h1 class="cpanel">playback</h1>
<p>
<button id="play">play</button>
<button id="pause">pause</button>
<button id="stop">stop</button>
</p>
</div>
<div class="panel_section">
<h1 class="cpanel">zoom</h1>
<p>
<button id="zoomIn">zoomIn</button>
<button id="zoomOut">zoomOut</button>
</p>
</div>
</div>
You might want to look at jQuery.dForm. It helps creating HTML and forms dynamically using JSON.
So i am assuming you mean your JSON contains the HTML string inside it.
lets say your JSON is:
{
"htmlString" : "<div> now thats smart! </div>"
}
you can render this in your HTML by writing your HTML as follows:
<html>
<head>
var myjson = {"htmlString" : "<div> now thats smart! </div>"}
<script type="text/javascript">
function loadHTML() {
document.getElementByTagName("body").innerHTML(myjson["htmlString"]);
}
</script>
</head>
<body onload='loadHTML()'>
</body>
</html>
Note that you can also use AJAX to fetch your JSON and render it
however, note that embedding HTML inside JSON when transporting from server is considered a security vulnerability.
Instead, you can fetch a partial HTML from the server directly by using AJAX and then replace portions of that HTML (template) with dynamic values by using javascrip and REST/SOA
hope this helps
EJS or embedded java script which is nice and fun. You could use a front end framework like backbone or facebook's React which is allot more complex. There are some good video tutorials on codeschool's node lesson for EJS. here is an example
var foo = {'city':'SF', 'party':'now'}
with EJS its as simple as:
<div> <p> going to <%= foo.city %> to party <%= foo.party %> </p></div>
to get text:' going to SF to party now'
With EJS, or my fav PEJS you can do if, switch, for(), Date() ..... you get the point. look Here for Pejs and also read EJS. Lots of cool stuff you can do
I am currently working on a project that lets users post comments with jquery and ajax. So far it is using Json and retunring several items, username, comment text, user photo url, comment ID number and stuff like that, I then need to use some sort of template to make all this data go into the correct div's before adding it all to the screen.
I am new to using javascript so this is a hard task for me. I am now considering the easy route.
Just have my PHP backend script return the whole block of code, div's and everything in place but I am wondering is this a bad idea? More importantly is it a bad idea with json?
Here is an example of a block of code that needs to be added to the screen when a comment is posted
<li class="admin" id="comment-1371">
<div class="photocolumn">
<!-- START Photo block -->
<div class="imageSub" style="width: 100px;">
<img class="male" src="http://cache2.mycrib.net/images/image_group34/0/39/T_653807517aff2b1f5662d865b40d87d527c8eb.jpg" alt="Something" width="100"/>
<div class="blackbg"></div>
<div class="label">JasonDavis</div>
</div>
<!-- END Photo block -->
</div><!-- END photocolumn -->
<div class="commenttext">
<p>02/12/3009</p>
<p>sample text for comment area!</p>
</div>
<!-- END COMMENTTEXT -->
</li>
I would say it depends on the situation/application. For instance I would use json and templating for a flight/hotel etc result screen. Why return 50k's worth of the same markup when a 4k json object will do and will allow for rapid clientside sort/filter. If you dont need quick clientside filtering/sorting then responding with dom fragments is ok. Horses for courses.
I don't see a problem with returning HTML via AJAX. A bonus of this is that you can generate most of the HTML in a view in PHP and still keep things fairly clean.
Tokenizing your data into an object is nice for re-use but can be overkill for a one-off.
Go the easy route, I can see no reasons of going with JSON array.