Alternative to jquery tmpl for inline html? - javascript

I am currently running into long inline html in my jquery in order to generate long html snippets on the fly.
Example:
var personalMessage = $("<div title='" + chatid + "' class='personalMessage'><div class='personalChatName'>" + fullname + "</div><div class='personalChatDialog'></div></div>")
$ContactsBar.prepend(personalMessage);
I want to add even more html in my personalMessage so i started to think that jquery.tmpl will be perfect for this, but jQuery discontinued it which i dont know why, but is there something new or an alternative that everyone uses now thats better? or is everyone still just using jquery.tmpl?

i came across this one just recently: t.js
however, if your needs are fairly limited you could just extend String with a simple template function:
String.prototype.template = function(obj) {
return this.replace(/\{\{([\w]+)\}\}/g, function(str, prop) {
return obj[prop];
});
};
alert('<div>my name is: {{last}}, {{first}}</div>'.template({first:'John', last:'Smith'}));
check it out

If you're looking for an HTML templating language in Javascript, you might want to look into Mustache.js.
It seems fairly popular.
Hope that helps.

Related

custom specifier in javascript/jquery

i want to format the numeric value in java script /jquery like that doing in C#. please refer below link.
http://msdn.microsoft.com/en-us/library/0c899ak8%28v=VS.90%29.aspx#SpecifierD
what are the formats currently we can do in javascript (currency, percentange,numeric).
i know that jquery.globalize script will do some formats like ($,%) i want to know what are the formats we can perform or implement in javascript.
is there any in build function for format the date time like format in C#
(dd/mm/yy)
Thanks,
Siva
Personally, I am not a great fan of the "plugins with jam" and "plugins with ketchup" approach to solving problems. As a general rule when you find yourself thinking "How can I do X in JavaScript like I do it in C# or PHP" it is well worth checking out PHP JS. In the present instance I suspect the sprintf function will do the trick.
Another useful function is this
String.prototype.format = function (args)
{
var newStr = this;
for (var key in args){newStr = newStr.replace('{' + key + '}', args[key]);}
return newStr;
}
//for example
console.log("You owe me ${aa}".format({aa:100}));
The string prototype extension is not my own work - I found it somewhere. Maybe here on SO, I cannot remember.

Is there a better way of creating elements and appending text to/around them?

I currently have a bunch of lines that look like:
txt = "Can't print the value for <span class='keyword'>"+arguments[1]+"</span> before it's set";
I'm then doing
$('#mydiv').append($('<div/>').html(txt));
This looks terrible and I need to escape any html inside arguments[1]
The only alternative I can think of is to make sure all the text is inside its own element:
var spans = [];
spans[0] = $('<span/>').text("Can't print the value for ");
spans[1] = $('<span/>').text(arguments[1]).className('keyword');
spans[2] = $('<span/>').text(" before it's set");
$('#mydiv').append($('<div/>').append(spans[0],spans[1],spans[2]));
This is quite a lot for just a simple line of text. Is there anything else I can do?
edit: This isn't something that should be handled by a templating engine. It's html generated by a javascript logging function.
If It's a consistent format, I'd add it as a normal string and then do a search for the keyword part.
$('<div/>')
.appendTo('#mydiv')
.html("Can't print the value for <span class='keyword'></span> before it's set")
.find('.keyword').text(arguments[1]);
If you will be continuing to create lots of HTML using JS, I would suggest working with a templating library. I am a recent convert, it took me a long time to understand the point. But seeing many successful sites (twitter,github,etc.) and the great John Resig promote and/or make heavy use of templating, i'm glad I stuck with trying to understand. Now I get it. It's for separation of concerns, keeping logic out of the view.
I'm using this very bare bones templating library: http://blueimp.github.com/JavaScript-Templates/ though the templating provided by underscore.js and mustache.js are more popular.
The advantage of the library i'm using is its really small, <1kb and is basically like writing php/asp code if you are familiar with those.
you can write HTML inside <script> tags without having to escape:
using your variable, txt, the syntax looks like this:
<script>
var data={txt : "Can't print the value for <span class='keyword'>"+arguments[1]+"</span> before it's set"};
<div>{%=o.txt%}</div>
</script>

how do I convert a querystring into a json object in jquery

This seems like a no brainer but surely there is either an internal js method or a jquery one to take a string like:
intTime=1324443870&fltOriginalAmount=0.00&strOriginalCurrency=GBP
...then a lot more vals and turn it into a JSON object?
I had a dig around this site and google and surprisingly drew blanks...
Anyone got an easy way to do this?
jQuery BBQ does exactly this. See $.deparam, "The opposite of jQuery.param, pretty much."
> var obj = $.deparam('intTime=1324443870&fltOriginalAmount=0.00&strOriginalCurrency=GBP')
> JSON.stringify(obj)
'{"intTime":"1324443870","fltOriginalAmount":"0.00","strOriginalCurrency":"GBP"}'
i used this hack...
$.parseJSON('{"' + qs.replace(/&/g, '","').replace(/=/g, '":"') + '"}');
demo here http://jsbin.com/niqaw/

Javascript-better method of writing HTML

This problem is about Javascript writing HTML code for video player. I think there are some faster methods(document.createElement,Jquery and etc). Please tell some better and faster methods for this procedure. Thanks in advance
function createPlayer(videoSource){
document.writeln("<div id=\"player\">");
document.writeln("<object width=\"489\" height=\"414\" >");
document.writeln("<param name=\"player\" value=\"bin- debug/FlexPlayer.swf\">");
//etc
document.writeln("</embed>");
document.writeln("</object>");
document.writeln("</div>");
}
Going native with document.createElement will be the fastest. However, if your markup is large, going this way makes it a maintenance nightmare. Also, it is not easy to 'visualize' things.
In those cases, you might want to go for a tradeoff with client side templating solutions such as jQuery templates or underscore templates or John Resig's microtemplating.
Another performance boost is to build your entire markup and add it to DOM at the very end (add children first, then add the parent to DOM).
There is a jQuery function I know of that allows you to create a template HTML snippet which you can later use repeatedly with only 1 or 2 lines of code, adding in variables and appending it to the page.
For this you will need jQuery (latest should be fine) http://jquery.com/
Docs for the tmpl function are here: http://api.jquery.com/jquery.tmpl/
For details on how to use it you'd be best reading an example on the jQuery docs, I've not used it myself so can't write you a good example but there is great stuff on the docs site.
Hope this helps
EDIT:
A less resource intensive way to acheive that function would be to, rather than writing each line in turn to the document, just append them all to a string and then write that once when you are finished.
Eg:
function createPlayer(videoSource){
var html="<div id=\"player\">";
html+="<object width=\"489\" height=\"414\" >";
//etc
document.writeln(html);
}
This is faster because writing a line to the document uses more resources than just appending a string in memory. For MAXIMUM SPEED you could even declare the html var outside of the function and just set it to the markup as one long string, then write it - i.e
var html;
function createPlayer(videoSource){
html="<div id=\"player\"><object width=\"489\" height=\"414\" >"; //and so forth
document.writeln(html);
}
If you can justify the larger download sizes I'd go for the jQuery solution if possible, it's generally a bit more manageable - I've done plenty script generated HTML in the past and it very quickly becomes a pain to maintain. Good luck
You can try this:
function createPlayer(videosource){
var div = document.createElement('div');
div.innerHTML = '<object width=\"489\" height=\"414\" >' +
'.......'
document.body.appendChild(div);
}
For general manipulation and addition of HTML I'd recommend jQuery. It makes the process much easier and quicker.
You will find more information on this here:
jQuery Manipulation Methods - http://api.jquery.com/category/manipulation/
jQuery Tutorials - http://docs.jquery.com/Tutorials

How to generate RDF/XML using a template in javascript?

I have some working Javascript code that generates an RDF/XML document using variables picked up from HTML fields:
...
peopleDoap += " <foaf:name>" + person_name + "</foaf:name>\n";
if (person_url != "") {
peopleDoap += " <foaf:homepage rdf:resource=\"" + person_url + "/\"/>\n";
}
if (person_pic != "") {
peopleDoap += " <foaf:depiction rdf:resource=\"" + person_pic + "/\"/>\n";
}
...
It's hard, looking at this code, to get any sense of what the output will look like (especially as this code is scattered amongst sub functions etc).
I'm wondering if there is an easy way that would enable me to have something like this:
...
<foaf:name>%person_name%</foaf_name>
<foaf:homepage rdf:resource="%person_url%"/>
<foaf:depiction rdf:resource="%person_pic%"/>
...
And then some substitution code. One slight complication is if fields are left blank, I will want to not generate the whole element. Ie, if person_url='', the above should generate as:
...
<foaf:name>%person_name%</foaf_name>
<foaf:depiction rdf:resource="%person_pic%"/>
...
I guess I could do this fairly naively by defining the template as a huge string, then performing a bunch of replaces on it, but is there anything more elegant? Mild preference for native Javascript rather than libraries, but happy to be convinced...
(Btw, yes, since this is RDF/XML, maybe there is a smarter way using some kind of RDF library. If you want to address that of the question instead, that's ok with me.)
Code is here.
Also, this is a widget running on a Jetty server. I don't think server-side code is an option.
I recommend using:
jQuery Templates
Mustache
John Resig's Micro-Templating
jQuery Templates are very powerful and nicely integrated with jQuery. That means that you can do things like this:
$.tmpl("Hello ${n}", {n: "World"}).appendTo('h1');
for the most simple stuff, or define templates in your HTML inside special script tags with custom MIME types, compile them, populate them with JSON data from AJAX calls, etc.
To add a bit of follow-up, I did implement John Resig's Micro-Templating (actually the refined version I posted earlier). However, I then backpedalled a bit. I found implementing control structures in the template is less readable than outside:
...
'<description xml:lang="en">#description</description>';
if (homepage) t +=
'<homepage rdf:resource="#homepage"/>';
...
rather than:
...
'<description xml:lang="en"><#= description #></description>' +
'<# if (homepage) { #>' +
'<homepage rdf:resource="<#= homepage =>"/>' +
'<# } #>';
...
I also ditched the microtemplating code for a simple substitution of variables, using #var rather than <# var #>.
Readability of templates like this is really critical, so I've done everything I could think of. In particular, keeping the javascript outside of the template lets syntax highlighting work, which is valuable to me.
That John Resig post also suggested burying the template in your HTML, in a but I preferred to keep it in my javascript, which is a separate .js.

Categories

Resources