Create HTML tag from Javascript object - javascript

What is the best method to change this object
{
src: 'img.jpg',
title: 'foo'
}
into a valid HTML tag string like this
<img src="img.jpg" title="foo" />
Solution 1
With jQuery this is easy; but complicated:
$('<img/>').attr(obj).wrap('<div/>').parent().html();
Any better ideas?

Why not:
$('<img/>', obj).get(0).outerHTML;
Fiddle
You do not need to wrap it in a div using multiple functions and get the html, just use get(0) to get the DOM element and outerHTML to get the element's html representation.
Unless you are using browsers really old you can rely on outerHTML
Here is a JSPerf to compare the performance diff between the approaches.

Perhaps slightly more concise than PSL's?
$('<img />',object)[0].outerHTML;

Simple with jquery
$("<div>").append($('<img />',object)).html();

If you are only doing one element, then this solution is overkill, but I thought I would post it anyway as I don't know what your project is.
Have you considered a JavaScript template engine? I've been playing around with Swig lately, as it is quite lightweight, but there are many options. Basically, you create a template, pass a JavaScript object, and the compiled template is executed, returning a string of HTML.
Example from Swig Documentation
Template
<h1>{{ pagename|title }}</h1>
<ul>
{% for author in authors %}
<li{% if loop.first%} class="first"{% endif %}>
{{ author }}
</li>
{% else %}
<li>There are no authors.</li>
{% endfor %}
</ul>
JavaScript to Render Template
var template = require('swig');
var tmpl = template.compileFile('/path/to/template.html');
tmpl.render({ // The return value of this function is your output HTML
pagename: 'awesome people',
authors: ['Paul', 'Jim', 'Jane']
});
Output
<h1>Awesome People</h1>
<ul>
<li class="first">Paul</li>
<li>Jim</li>
<li>Jane</li>
</ul>

Making html elements based out of objects containing attribute-attribute values such as
{
src: 'img.jpg',
title: 'foo'
}
almost completely falls into the paradigm of cook.js.
The command which you would issue with cook would be:
img ({
src: 'img.jpg',
title: 'foo'
})
If the attribute details are stored as given in your example,
in a variable obj then:
img(obj)
For more details check it out at cook.relfor.co.

Here's how you make it as a string:
var img = '<img ',
obj = { src : 'img.jpg', title: 'foo' };
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
img += prop + '=' + '"' + obj[prop] + '" ';
}
}
img += '/>';
http://jsfiddle.net/5dx6e/
EDIT: Note that the code answers the precise question. Of course it's unsafe to create HTML this way. But that's not what the question asked. If security was OP's concern, obviously he/she would use document.createElement('img') instead of a string.
EDIT 2: For the sake of completeness, here is a much safer way of creating HTML from the object:
var img = document.createElement('img'),
obj = { src : 'img.jpg', title: 'foo' };
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
img.setAttribute(prop, obj[prop]);
}
}
http://jsfiddle.net/8yn6Y/

Related

JsRender - How to Translate templates? (Best Practices)

Im rokiee using Jsrender, I would like to know which is the best way to translate my templates
I have templates like this:
_welcome.tmpl.html:
<div> Hello, {{:name}}</div>
<div> welcome to {{:place}}</div>
and i read daat from file like this:
welcome.json:
{
"name": "David"
"place": "wien"
}
Until here, works fine.
So, now i would like to translate the words "hello" and "welcome to" in diferrents languages. But my system its really ugly and inefficient.
I have different files that i load depends on "lang" attribute. For expample
lang="EN" im going to load:
english_vars.js
var t_hello = "Hello";
var t_msg = "Welcome to";
if lang="es" im going to load:
spanish_vars.js
var t_hello = "Hola";
var t_msg = "Bienvenido a";
Then my templates looks like this:
var wellcomeTemplate = `
<div>`+t_hello+`, {{:name}}</div>
<div>`+t_msg+` {{:place}}</div>`
There are any way to improve this templates engine translations?
Note: Translations MUST NOT come in the same .json that DATA
If you have your localized dictionary as JSON or a JavaScript object (hash):
var terms = {
hello: "Hola",
welcome: "Bienvenido a"
};
then you can pass in the terms separately from the data, as helper variables:
<script id="tmpl" type="text/x-jsrender">
<div>{{:~hello}}, {{:name}}</div>
<div>{{:~welcome}} {{:place}}</div>
</script>
like this:
var data = {
name: "John",
place: "Madrid"
};
var html = $.templates("#tmpl").render(data, terms);
When you change language, pass in the appropriate localized terms.
See http://www.jsviews.com/#helpers
An alternative possibility is to translate the template for each language, using JsRender itself to translate. Simply change the delimiters for the translation step, so you only translate the terms, without changing the other tags:
<script id="baseTmpl" type="text/x-jsrender">
<div><%:hello%>, {{:name}}</div>
<div><%:welcome%> {{:place}}</div>
</script>
then:
$.views.settings.delimiters("<%", "%>");
var localizedTemplate = $.templates("#baseTmpl").render(terms);
$.views.settings.delimiters("{{", "}}");
var html = $.templates(localizedTemplate).render(data);
See http://www.jsviews.com/#settings/delimiters
Both approaches are shown in this jsfiddle

Combining strings to a bound variable in Ember.js

I need to include images in my Ember.js/Handlebars template.
I was using <img {{bindAttr src="short_name"}}> which would work if the image was exactly the value of short_name and in the root directory.
However, I need to construct the img src like this:
'/images/avatars' + short_name + '_avatar.jpg'
How would this be accomplished in ember/handlebars?
Considering that short_name doesn't change, you could do it like this:
<img src="/images/avatars{{unbound short_name}}_avatar.jpg">
But if short_name change a lot, you should use a computed property like so:
var SomeModel = Ember.Object.extend({
shortName: null,
imgSrc: function() {
var shortName = this.get('shortName');
return '/images/avatars' + shortName + '_avatar.jpg';
}.property('shortName')
});
And then on your template:
<img {{bindAttr src="imgSrc"}}>

Ember.js property and ArrayController in template

I've got a setup like this in Ember:
App.ListObject = Ember.Object.create({
knownThings: function() {
var ot = this.openThings.get('content');
var ct = this.closedThings.get('content');
var kt = ot.concat(ct);
var known = Ember.ArrayController.create({content: kt});
return known;
}.property(),
openThings: Ember.ArrayController.create({
content: []
}),
closedThings: Ember.ArrayController.create({
content: []
}),
})
Basically, known things is the combined arrays of openThings and closedThings. I can't seem to figure out how to iterate over knownThings in the template. Just doing
{{#each App.ListObject.knownThings }}
Does not work as the property needs to be accessed like App.ListObject.get('knownThings') but that doesn't work in the template unless I'm doing something terribly wrong. Iterating over the other attributes in the template does work (open and closed things)
So, how would you iterate over knownThings in the template?
Slight Modifications needed...
Firstly,
knownThings: function() {
//use get to retrieve properties in ember, Always !
var ot = this.get('openThings').get('content');
//var ot = this.get('openThings.content') if you are using latest ember
var ct = this.get('closedThings').get('content');
//var ot = this.get('closedThings.content') if you are using latest ember
var kt = ot.concat(ct);
var known = Ember.ArrayController.create({content: kt});
return known;
//Add dependencies to keep your knownThings in sync with openThings & closedThings if at all they change in future
}.property('openThings', 'closedThings')
Coming to Handlebars iterate using
//you forgot content property, and in handlebars you don;t need to use get, dot operator is enough
{{#each App.List.knownThings}}
Let me know if this works...
Update
Working Fiddle...
Unless I didn't understand what you're saying, I think you should have ListObject extending Em.ArrayController instead of Em.Object. Also, if your property depends on content, it should be .property('content.#each'). If you're using the router, your template should look like {{#each thing in controller.knownThings}} and you use {{thin.something}}, if not using router, then {{#each item in App.listObject.knownThings}}. Also, openThings and closedThings don't seem to be correct and the way you're accessing them is wrong too.
I didn't write a fiddle for this specific case cause I don't really know what you're trying to do, but take a look at this fiddle, specifically at App.ResourcesController and the template 'resources-view':
Controller:
// ...
App.ResourcesController = Em.ArrayController.extend({
content: [],
categories: ['All', 'Handlebars', 'Ember', 'Ember Data', 'Bootstrap', 'Other'],
categorySelected: 'All',
filtered: function() {
if(this.get('categorySelected') == "All") {
return this.get('content');
} else {
return this.get("content")
.filterProperty(
"category",
this.get('categorySelected')
);
}
}.property('content.#each', 'categorySelected'),
filteredCount: function() {
return this.get('filtered').length;
}.property('content.#each', 'categorySelected'),
hasItems: function() {
return this.get('filtered').length > 0;
}.property('filteredCount')
);
// ...
Template:
<script type="text/x-handlebars" data-template-name="resources-view">
<h1>Ember Resources</h1>
{{#view Bootstrap.Well}}
The following is a list of links to Articles, Blogs, Examples and other types of resources about Ember.js and its eco-system.
{{/view }}
{{view Bootstrap.Pills contentBinding="controller.controllers.resourcesController.categories" selectionBinding="controller.controllers.resourcesController.categorySelected"}}
<i>{{controller.filteredCount}} Item(s) Found</i>
{{#if controller.hasItems}}
<ul>
{{#each resource in controller.filtered}}
<li>
<a {{bindAttr href="resource.url"
target="resource.target"
title="resource.description"}}>
{{resource.htmlText}}
</a>
</li>
{{/each}}
</ul>
{{else}}
{{#view Bootstrap.AlertMessage type="warning"}}
Couldn't find items for {{controller.categorySelected}}
{{/view}}
{{/if}}
</script>

knockout js remove does not work

I'm trying to get my head around observables in knockout js!
However, I'm facing a problem implementing the remove function on an observable array.
My js is as follow:
$(function () {
var data = [{ name: "name1" }, { name: "name2" }, { name: "name3"}];
var viewModel = {
namesList: ko.observableArray(data),
nameToAdd: ko.observable("name4"),
myCustomAddItem: function () {
this.namesList.push({ name: this.nameToAdd() });
},
myCustomRemove: function () {
console.log("before + " + this.nameToAdd());
this.namesList.remove(this.nameToAdd());
console.log("after + " + this.nameToAdd());
}
};
ko.applyBindings(viewModel);
});
and my html is:
Name To add/remove <input type="text" data-bind="value: nameToAdd, valueUpdate: 'afterkeydown'"/>
<ul data-bind="template: {name: 'listTemp1', foreach :namesList}">
</ul>
<p>
<button data-bind="click: myCustomAddItem">Add Item</button>
<button data-bind="click: myCustomRemove">Remove Item</button>
<script id="listTemp1" type="text/html">
<li data-bind="text:name"> </li>
</script>
</p>
my myCustomAddItem works fine, but not the myCustomRemove. I also have put a console.log before and after the this.namesList.remove(this.nameToAdd()); to see if anything's wrong there, but I cannot see any error in there. When I click the "Remove Item" button, firebug console shows the logs but the item's not removed from the list.
Any help appreciated
The parameter to remove should be a function which returns true or false on whether to remove something.
It works quite similarly to the filter function.
In your case, something like this should work:
myCustomRemove: function () {
console.log("before + " + this.nameToAdd());
var nameToAdd = this.nameToAdd();
this.namesList.remove(function(item) {
//'item' will be one of the items in the array,
//thus we compare the name property of it to the value we want to remove
return item.name == nameToAdd;
});
console.log("after + " + this.nameToAdd());
}
[this should be a comment on Jani answer, but I can't still comment on others post, sorry]
Just a small clarification: technically you can call remove() passing the element to remove, see section "remove and removeAll" on http://knockoutjs.com/documentation/observableArrays.html.
the problem with your code is that the elements in 'data' array are objects (containing a property called 'name'), and you are asking to remove from the array the string "name4" (or whatever 'nameToAdd' contains).
You can be tempted to create a new object to pass to remove, like this:
// old code
//this.namesList.remove(this.nameToAdd());
this.namesList.remove({ name: this.nameToAdd() });
but this still fails, because the way javascript object equality works (see, for example: How to determine equality for two JavaScript objects?).
So, in the end you need to use the function anyway.
In this simple example, you can also convert the 'namesList' array to a simple array of strings, and bind "$data" in the template. see http://jsfiddle.net/saurus/usKwA/.
In a more complex scenario, maybe you can't avoid using objects.
[observableArray].remove(function(item) { return item.[whatever] == [somevalue] ; } );

How to bind click handlers to templates in knockoutjs without having a global viewModel?

I'm very new to KnockoutJs so I'm hoping that there is a well known best practice for this kind of situation that I just haven't been able to find.
I have a view model that contains an array of items. I want to display these items using a template. I also want each item to to be able to toggle between view and edit modes in place. I think what fits best with Knockout is to create the relevant function on either the main view model or (probably better) on each item in the array and then bind this function in the template. So I have created this code on my page:
<ul data-bind="template: {name: testTemplate, foreach: items}"></ul>
<script id="testTemplate" type="text/x-jquery-tmpl">
<li>
<img src="icon.png" data-bind="click: displayEditView" />
<span data-bind="text: GBPAmount"></span>
<input type="text" data-bind="value: GBPAmount" />
</li>
</script>
<script>
(function() {
var viewModel = new TestViewModel(myItems);
ko.applyBindings(viewModel);
})();
</script>
And this in a separate file:
function TestViewModel(itemsJson) {
this.items = ko.mapping.fromJS(itemsJson);
for(i = 0; i < this.items.length; ++i) {
this.items[i].displayEditView = function () {
alert("payment function called");
}
}
this.displayEditView = function () {
alert("viewmodel function called");
}
};
Due to the environment my JS is running in I can't add anything to the global namespace, hence the annonymous function to create and set up the view model. (There is a namespace that I can add things to if it is necessary.) This restriction seems to break all the examples I've found, which seem to rely on a global viewModel variable.
P.S. If there's an approach that fits better with knockoutJS than what I am trying to do please feel free to suggest it!
When your viewModel is not accessible globally, there are a couple of options.
First, you can pass any relevant methods using the templateOptions parameter to the template binding.
It would look like (also note that a static template name should be in quotes):
data-bind="template: {name: 'testTemplate', foreach: items, templateOptions: { vmMethod: methodFromMainViewModel } }"
Then, inside of the template vmMethod would be available as $item.vmMethod. If you are using templateOptions as the last parameter, then make sure that there is a space between your braces { { or jQuery templates tries to parse it as its own.
So, you can bind to it like:
<img src="icon.png" data-bind="click: $item.vmMethod" />
The other option is to put a method and a reference to anything relevant from the view model on each item. It looks like you were exploring that option.
Finally, in KO 1.3 (hopefully out in September and in beta soon) there will be a nice way to use something like jQuery's live/delegate functionality and connect it with your viewModel (like in this sample: http://jsfiddle.net/rniemeyer/5wAYY/)
Also, the "Avoiding anonymous functions in event bindings" section of this post might be helpful to you as well. If you are looking for a sample of editing in place using a dynamically chosen template, then this post might help.
This is for those asking how to pass variable methods (functions) to Knockout Template. One of the core features of Templating is the consuming of variable data, which can be String or function. In KO these variables can be embedded in data or foreach properties for the Template to render. Objects embedded in data or foreach, be it String, function etc, can be accessed at this context using $data.
You can look at this code and see if it can help you to pass functions to Knockout Template.
function ViewModel() {
this.employees = [
{ fullName: 'Franklin Obi', url: 'employee_Franklin_Obi', action: methodOne },
{ fullName: 'John Amadi', url: 'employee_John_Amadi', action: methodTwo }
],
this.methodOne = function(){ alert('I can see you'); },
this.methodTwo = function(){ alert('I can touch you'); }
}
ko.applyBindings(new ViewModel());
<ul data-bind="template: { name: employeeTemplate, foreach: employees }" ></ul>
<script type="text/html" id="employeeTemplate">
<li><a data-bind="attr: { href: '#/'+url }, text: fullName, click: $data.action"></a></li>
</script>
If you want to serve multiple Template constructs you can introduce a switch method to your ViewModel like this, and use as property to introduce alias for each item (employee). Make sure you add the switch key, linkable, to the item object.
...
this.employees = [
{ fullName: 'Franklin Obi', linkable : false },
{ fullName: 'John Amadi', url: 'employee_John_Amadi', action: methodTwo, linkable : true }
],
this.methodLinkTemplate = function(employee){return employee.linkable ? "link" : "noLink"; } //this is a two way switch, many way switch is applicable.
...
Then the id of the Template forms will be named thus;
<ul data-bind="template: { name: employeeTemplate, foreach: employees, as: 'employee' }" ></ul>
<script type="text/html" id="noLink">
<li data-bind="text: fullName"></li>
</script>
<script type="text/html" id="link">
<li><a data-bind="attr: { href: '#/'+url }, text: fullName, click: $data.action"></a></li>
</script>
I have not ran this codes but I believe the idea can save someones time.

Categories