Home Ask Login Register

Developers Planet

Your answer is one click away!

qwertyuiop February 2016

generating HTML with javascript that contains php and ifs

I have a large amount of HTML and CSS which contains some PHP (session based content) this PHP is a must. I need that session information (no cookies wont do).

The html and CSS are standard divs I am looking at this previous question: Is there a best practice for generating html with javascript

which gives me the answer I need, if I was using just HTML and CSS, but what about if I need to use JS if statements to chose what part of the template needs to be different and what if I need to use PHP to do the same?

I am moving my code away from heavy server side scripting and moving as much as I can to front end processing, but the issue is I need to have some PHP and if statements (js if statements) within the $.template

can I use PHP variables in a JS templating system and how do I use JS IF statements within the templating function?

var moo = 1
var T = $.template('<div>This is code, but what is moo?. if(moo == 1){moo was 1..}else{moo was not 1}</div>')


kosmos February 2016

As I commented, you can declare and check your variables before using it.


var moo = 2 + 2 == 4 ? "yes moo" : "no moo";
var T = $.template('<div>This is code, but what is moo?. Moo is '+ moo +'</div>');

But if you are working with large data, you should consider to use a string variable and concatenate the new strings as needed:

var str = "<div>";
if( moo == 4 ) str += "moo equals 4";
else str += "moo NOT equals 4";
str += "</div>";

// And when you have your string completed...
var T = $.template(str);

By this way you can concatenate all you need without headaches.

Post Status

Asked in February 2016
Viewed 1,673 times
Voted 8
Answered 1 times


Leave an answer

Quote of the day: live life