jsrender Template method - javascript

I have use the following code snippet to render the data.
Code snippet:
<body>
<div id="myGrid" style="border:1px solid red; width:500px;height:600px;">
</div>
<script id="template" type="text/x-jsrender">
<div><div>{{:Name]}}</div></div>
</script>
<script type="text/javascript"7>
var helpers = {};
helpers["templateMethod"] = Test;
$.views.helpers(helpers);
var data = [{ "ID": 1, "Name": "Raja" },
{ "ID": 2, "Name": "sekar" },
{ "ID": 3, "Name": "Ram" }
]
var test = $("#template").render(data);
$("#myGrid").html(test);
function Test() {
}
</script>
</body>
In this case i want to get the each div element while rendering for customization.
How to get this div element while rendering.

If I understand your question, you want to change the to where foo changes in each div (and "class" is just an example). To do that, you would need either a helper, a tag, or another template. Each have advantages.
Here is the link for tags. I think that is most likely what you want.

Related

Data context on JsViews' include tag

I made a snippet to show the issue I'm facing:
<html>
<head>
<title>Demo 1 JsViews</title>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsviews/0.9.90/jsviews.min.js"></script>
</head>
<body>
<script id="template" type="text/x-jsrender">
<p>{{:property}}</p>
{^{on ~root.testFunction}}PUSH ME!{{/on}}
{{for nestedObjects}}
{{include #data tmpl="#template-2"/}}
{{/for}}
</script>
<div id="container"></div>
<script id="template-2" type="text/x-jsrender">
<p>{{:~root.property}}</p>
{^{on ~root.testFunction}}PUSH ME!{{/on}}
</script>
<div id="container-2"></div>
<script>
data = {
property : "PARENT",
testFunction : function(){ alert(this.property); },
nestedObjects : [
{
id: 0,
property: "CHILD1",
testFunction : function(){ alert(this.property);}
},
{
id: 1,
property: "CHILD2",
testFunction : function(){ alert(this.property);}
}]
};
/**
* Funciones
*/
$(document).ready(function(){
var tmpl = $.templates("#template");
tmpl.link("#container", data);
});
</script>
</body>
</html>
As you can see, in '#template-2' it's taking the properties from main data object, not from each nestedObjects' item. I know this would be the normal behaviour.
Is there a way to make include tag to take each nestedObjects' item and not the whole data object as context?
I know that if I remove the '~root' modifiers in '#template-2' it will work as expected, but I need it to work with '~root' modififer if possible.
Thanks in advance :)
After trying many things, I managed to get it working in another way using a helper object, if someone has a similar issue feel free to contact me :).
~root is a built-in helper that points to the top-level data that you passed to the link() or render() method. See
http://www.jsviews.com/#contextualparams#root.
So you can't change it to have it point somewhere else. But you can create your own helpers (not using the reserved root name), such as:
{{include #data ~myroot=#data tmpl="#template-2"/}}
and in template-2 write
{{:~myroot.property}}

binding object to templates with javascript

I have been playing with jquery and templates, and I cobbled together a simple template binding system:
<script type="text/template" id="Template">
<div>{0}</div>
</script>
and...
var buffer = '';
var template = $("#Template").html();
response.Data.forEach(function(arrayElement)
{
buffer += template.format(arrayElement.p1,);
});
$("#ListOutput").html(buffer);
My question is: Is there a more natural way that I can take a JSON object, such as:
{"user": { "id": "1","name": "bob" }}
And use a more natural binding sintax, such a this:
<script type="text/template" id="Template">
<div>{user.name}</div>
</script>
straight JS or jquery would be idea. I know that some of the more complex data binding tools like Angular provide these features, but the complexity of some of the data binding plugins makes my head swim. Anything based on node is right out.
Is there some native feature I don't know about that makes this easy?
If you can use ES2015 "template strings".
<script type="text/template" id="Template">
<div>${user.name}</div>
</script>
You have not added response array, so I am assuming it as
[
{"user": { "id": "1","name": "bob" }},
{"user": { "id": "2","name": "Some Name" }}
]
var buffer = '';
var template = $("#Template").html();
response.Data.forEach(function(arrayElement) {
var user = arrayElement.user;
buffer += eval('`' + template + '`');
});
$("#ListOutput").html(buffer);

Image Gallery hosted in Google Drive Folder

I've been looking for a way to create a gallery on a website with images from a folder in my google drive. Which I have shared here: https://drive.google.com/drive/u/0/folders/0Bwx-OwnNeIvwRldSVlU5SGN0dGs
inside it is a simple HTML, and a gallery folder with pictures of monster trucks and cute animals. And the goal is here to create a gallery where people can upload images of well; monster trucks and cute animals.
I've been searching for all kinds of methods of achieving this and this is what I have found so far:
In short what I am trying to achieve is to get the id's of images in a publicly shared folder in my G-Drive. Then use those id's to create a gallery via JS in an HTML.
What my HTML looks like now:
index.html
<h1>Cute Animals & <br>
Monster Vehicles</h1>
<div id="gallery">
<!-- all divs will append here -->
</div>
What I researched on the Drive SDK:
I've been using the "try it" section here to figure out what i need to do. https://developers.google.com/drive/v2/reference/children/list#examples
Request result: GET https://www.googleapis.com/drive/v2/files/0Bwx-OwnNeIvwRG5rNzZ6OURSNEk/children?fields=items%2Fid
Response result:
200 OK
- SHOW HEADERS -
{
"items": [
{
"id": "0Bwx-OwnNeIvwaFZXVzVmMl9ILUU"
},
{
"id": "0Bwx-OwnNeIvwVk1DTEpnR0J6VHc"
},
{
"id": "0Bwx-OwnNeIvwblBHLVEza0hxY2s"
},
{
"id": "0Bwx-OwnNeIvwTkZZVXp0dDg4bXc"
},
{
"id": "0Bwx-OwnNeIvwZTN1YzZrcm53eFE"
},
{
"id": "0Bwx-OwnNeIvwYkZ5ZXpjWHhKcFk"
}]}
What I would like for the script to do:
script.js
var imageIds = <!-- ids from the the response --> ;
var x = imageIds.length;
for (var i = 0; i < x; i++) {
<!-- create a <div> -->
}
//See below*
Create a div: In the for loop it will create a <div> with a specific "class" and an <img> inside that div, with a "src="http://drive.google.com/uc?export=view&id=IMAGE-ID" where the "IMAGE-ID" was gotten from the "Response". the <div> will then be appended to <div id="gallery"> in the index.html.
What I would like for the end HTML do look like:
index.html:
<h1>Cute Animals & <br>
Monster Vehicles</h1>
<div id="gallery">
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwaFZXVzVmMl9ILUU">
</div>
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwVk1DTEpnR0J6VHc">
</div>
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwblBHLVEza0hxY2s">
</div>
<!-- and so on ... -->
</div>
What I am unsure of now, is how this needs to be authenticated to get the image-ids from the G-Drive folder. This could be hosted from Google Drive itself with their hosting links, or it could be created through Google Apps Script, and the functionality to serve HTML there, and that would make the authentication easier as you can get everything from drive directly.
I don't understand why this is no where to be found, that does not involve a payment. It would be great if everyone had the opportunity to create image galleries from images in a G-Drive folder.
Would really like your help on this one. Thanks alot.
Firstly, about the code itself, it would be something like that:
document.addEventListener('DOMContentLoaded', function() {
var response = {
"items": [{
"id": "0Bwx-OwnNeIvwaFZXVzVmMl9ILUU"
}, {
"id": "0Bwx-OwnNeIvwVk1DTEpnR0J6VHc"
}, {
"id": "0Bwx-OwnNeIvwblBHLVEza0hxY2s"
}, {
"id": "0Bwx-OwnNeIvwTkZZVXp0dDg4bXc"
}, {
"id": "0Bwx-OwnNeIvwZTN1YzZrcm53eFE"
}, {
"id": "0Bwx-OwnNeIvwYkZ5ZXpjWHhKcFk"
}]
};
var imageIds = response.items.map(function(item) {
return '<div class="brick"><img src="http://drive.google.com/uc?export=view&id=' + item.id + '"></div>';
});
document.getElementById('gallery').insertAdjacentHTML('afterbegin', imageIds.join(''));
});
<div id="gallery"></div>
About the authorization, take a look at their documentation.

Rendering one mustache partial multiple times with different data

I have two objects that I want to render side by side. There is never a case where I will want to render more, or less than two. My model is setup like so:
{
obj1: {...},
obj2: {...}
}
Using mustache templates, I want to render each object using the same partial:
<div>
<h1>Object 1</h1>
{{>objPartial}}
</div>
<div>
<h1>Object 2</h1>
{{>objPartial}}
</div>
However, mustache doesn't seem to support passing a context to the partial. Doing something like {{>objPartial obj1}} seems like it should be supported, but I can't find any documentation on setting a context for a partial.
Is this sort of thing supported? If not, how can I accomplish the same effect without duplicating the partial (objPartial1 and objPartial2)?
The syntax I think you are looking for is not {{>objPartial obj1}}, but rather it should be
{{#obj1}}
{{>objPartial}}
{{/obj1}}
The syntax for {{#}} isn't only for arrays - for non array objects the object becomes part of the current scope.
I've forked maxbeatty's example and modified it to show this syntax:
<script type="template/text" id="partial">
<ul>
{{#name}}
<li>{{.}}</li>
{{/name}}
</ul>
</script>
<script type="template/text" id="main">
<div>
<h1>Stooges</h1>
{{#object1}}
{{>objPartial}}
{{/object1}}
</div>
<div>
<h1>Musketeers</h1>
{{#object2}}
{{>objPartial}}
{{/object2}}
</div>
</script>​
<script type="text/javascript">
var partial = $('#partial').html(),
main = $('#main').html(),
data = {
object1: {
name: ["Curly", "Moe", "Larry"]},
object2: {
name: ["Athos", "Porthos", "Aramis", "D'Artagnan"]}
},
html = Mustache.to_html(main,data, {
"objPartial": partial
});
document.write(html);
</script>
Link to jsfiddle: http://jsfiddle.net/YW5zF/3/
You could adjust your model to include the h1 and div so you could loop over a list sending different data to objPartial each time
<script type="template/text" id="partial">
<ul>
{{#name}}
<li>{{.}}</li>
{{/name}}
</ul>
</script>
<script type="template/text" id="main">
{{#section}}
<div>
<h1>{{title}}</h1>
{{>objPartial}}
</div>
{{/section}}
</script>
<script type="text/javascript">
var partial = $('#partial').html(),
main = $('#main').html(),
data = {
section: [
{
title: "Object 1",
name: ["Curly", "Moe", "Larry"]},
{
title: "Object 2",
name: ["Athos", "Porthos", "Aramis", "D'Artagnan"]}
]
},
html = Mustache.to_html(main,data, {
"objPartial": partial
});
document.write(html);
</script>
See it on jsFiddle

How to translate into other languages my web page?

How can I translate my web pages? Actually what technology or what scripting-if require- should be used? For info; I have all translated text. But I do not want to create something like clone site for other language.
I used just javascript -including jquery .
Just using JavaScript...
<script type="text/javascript">
// JSON-formatted, potentially read from a database
var article = {
title: {
en_US: "Article Title",
fr_FR: "Titre de l\'Article"
},
content: {
en_US: "Content of the Article.",
fr_FR: "Contenu de l\'Article."
}
}
// simple function to write the info to the page
function get_i18n(item, lang) {
document.write(article[item][lang]);
}
</script>
<!-- English Version -->
<div class="story">
<h1 class="title"><script>get_i18n('title','en_US');</script></h1>
<p class="content"><script>get_i18n('content','en_US');</script></p>
</div>
<!-- French Version -->
<div class="story">
<h1 class="title"><script>get_i18n('title','fr_FR');</script></h1>
<p class="content"><script>get_i18n('content','fr_FR');</script></p>
</div>
Please Note: This isn't a very graceful solution. I'm sure there's a prettier method...
You actually mean "how to build multi lingual website" as you already have the "translated text" as you call it.
One way is to put the text inside containers then using client side code change the containers contents to the proper text according to selected language, having arrays with translated text in each language.
If you have server side language at your disposal it would be much better though - do you have such thing?
Using CSS attribute selectors:
<style type="text/css">
// hides all French blocks by default
div.story[lang="fr"] {
display: none;
}
// hide all English blocks
body[lang="fr"] div.story[lang="en"] {
display: none;
}
// show all French blocks
body[lang="fr"] div.story[lang="fr"] {
display: block;
}
</style>
<!-- Change this to the language of the blocks you want to display -->
<body lang="fr">
<!-- English block, shown by default -->
<div class="story" lang="en">
<h1 class="title">Article Title</h1>
<p class="content">Content of the Article.</p>
</div>
<!-- French block, hidden by default -->
<div class="story" lang="fr">
<h1 class="title">Titre de l'Article</h1>
<p class="content">Contenu de l'Article.</p>
</div>
</body>
This setup defaults to showing all English blocks, unless lang="fr" is set on the <body> tag.
Of course, you'll still need some way to modify the lang attribute of the <body> tag...
It would take too long for JavaScript to translate your site. I'd say find some software that can translate HTML files and keep both versions on your server. I know this isn't what you want, but it's the only practical way right now.
You can use Cloud Translation, it's a free and open-source project from Angry Monkey Cloud: https://github.com/angrymonkeycloud/CloudTranslation.
You should add a reference to jQuery first, then to the CloudTranslation JavaScript file:
<script crossorigin="anonymous" src="https://cdn.amcapi.com/translation/cloudtranslation-1.0.0.min.js"></script>
And add the configuration within the HTML head as follows:
<script type="application/json" id="CloudTranslationConfig">
{
"Settings": {
"DefaultLanguage": "en",
"TranslatorProvider": "Azure", // not required if you filled in all translations
"TranslatorProviderKey": "{Your Microsoft Azure Translator Key}", // not required if above is empty
"UrlLanguageLocation": "Subdirectory"
},
"Languages": [
{
"Code": "en",
"DisplayName": "English"
},
{
"Code": "ar",
"DisplayName": "Arabic",
"Direction": "rtl"
}
],
"Translations": [
{
"en": "Home",
"ar": "الصفحة الرئيسية"
},
}
</script>
and add your own custom select (dropdown) having the class "CloudTranslationSelect" (you can customize the style of your select the way you want).
More information found on https://www.angrymonkeycloud.com/translation
I have improved the first answer a bit. Just use a function to set the lanaguage value in localStorage and then get the language from there and dynamically change the HTML with the global variable lgn.
<script type="text/javascript">
// JSON-formatted, potentially read from a database
var article = {
title: {
en_US: "Article Title",
fr_FR: "Titre de l\'Article"
},
content: {
en_US: "Content of the Article.",
fr_FR: "Contenu de l\'Article."
}
}
// simple function to write the info to the page
function get_i18n(item, lang) {
document.write(article[item][lang]);
}
var lng; //global variable
if (localStorage.getItem('lng') == null) { //if I have no language saved just load the English language
lng = 'en_US';
localStorage.setItem('lng', lng);
}
if(localStorage.getItem("lng") == 'en_US'){
lng = 'en_US';
}
if(localStorage.getItem("lng") == 'fr_FR'){
lng = 'fr_FR';
}
console.log(lng);
function get_i18n(item, lng) {
document.write(article[item][lng]);
}
</script>
<div class="story">
<h1 class="title"><script>get_i18n('title',lng);</script></h1>
<p class="content"><script>get_i18n('content',lng);</script></p>
</div>

Categories