Link to home
Create AccountLog in
Avatar of interclubs
interclubs

asked on

Simple Javascript Template...

I'm looking to do a simple javascript template function, something would work like this:

var data = {name: 'john', age:'22'};

var template = 'Hi {name} what is your {age}';

parseTemplate(date, template);

Which would return:
"Hi john what is your 22'
 
But obviously I would want it to work with any data/template being passed in, not jus this one example.
Avatar of dr_Pitter
dr_Pitter

Hi,

i would suggest jQuery and the jQuery-templating-plugin.
http://api.jquery.com/jquery.tmpl/

I've been working with it for a while and it fullfills everything i need
Avatar of interclubs

ASKER

sadly, not an option for this.
Maybe something like this?
<!DOCTYPE html>
<html>
<head><html>
<head>
<title></title>
<script type="text/javascript">

function hiMsg(x,y){
	var msgTxt = 'Hi ' + x + ', what is your ' + y + '?';
	alert(msgTxt);
}
</script>
</head>
<body>

<form name="usrform">

<input type="button" value="Show Message from Button" onClick="hiMsg('John',22)">
<br><br>

Name:
<input type="text" name="usrnm" value="Bill">
<br>

Age: <input type="text" name="usrage" value="33">
<br>

<input type="button" value="Show Message From Text Fields" onClick="hiMsg(usrnm.value,usrage.value)">


</form>

</body>
</html>

Open in new window

Avatar of leakim971
For example :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript">
var data = {name: 'john', age:'22'};
var template = 'Hi {name} what is your {age}';

function parseTemplate(d,t) {
	return t.replace(/{[^{]*}/g, function($1) {
		return d[$1.substr(1,$1.length-2)];
	});
}

alert( parseTemplate(data, template) );
</script>
</head>

<body>
</body>
</html>

Open in new window

Another one :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript">
var data = {name: 'john', age:'22'};
var template = 'Hi {name} what is your {age}';

function parseTemplate(d,t) {
	for(var j in d) {
		t = t.replace(new RegExp("{" + j + "}", "g"), d[j])
	}
	return t;
/*	return t.replace(/{[^{]*}/g, function($1) {
		return d[$1.substr(1,$1.length-2)];
	});*/
}

alert( parseTemplate(data, template) );
</script>
</head>

<body>
</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer