Templates in JS? - php

All we like simple, structured code that is easy to comply with. We try to bring a difference between appearance and logics. In PHP, for instance, we can use a template mechanism, i.e. create an html-formatted file with php tags that uses some predefined variables that get ready for use through a logic resposible script.
Is there some analog for JavaScript?
What methods do you use to create dynamic content of certain type? (For example list items, complex forms that can be repeated several times)

There are many js template engin as below. Choose as you want. Handlebars is my suggestion.
Handlebars. http://handlebarsjs.com/
jquery template. http://api.jquery.com/jQuery.template/
Ejs http://embeddedjs.com/.
Underscore has template engin. http://documentcloud.github.com/underscore/#template
trimpath http://code.google.com/p/trimpath/wiki/JavaScriptTemplates
John Resig's micro template engin. http://ejohn.org/blog/javascript-micro-templating/
mustaches is also a good one. https://github.com/janl/mustache.js/

Underscore.js has simple templating mechanism as well. (And I think it must be in every javascript developer's toolbox).
jQuery's is more sophisticated, though - and probably more useful (Update: but now is deprecated).

I've used things like js-template for client side templates. For server side, whatever template mechanism was present in the system at hand could usually be applied to plain text javascript files.

Try looking into jQuery Templates. It is one of the many solutions available.

Related

HTML templating like PHP templating

I know things like these have been asked and answered several times before, is it just that I can't grasp the idea easily or too hard to accept that things are really like this and that.
I know that HTML is used for Front-End where the tedious work is done in the Client, and PHP is working behind the scenes (Server-Side). With so many regulations, instruction, standards, so on and so forth.. I believed I have already confused myself with these stuffs, making things (new and old) hard for me to chew and understand especially when it comes to their best uses...
Anyway, I have created a web application based on the concept of MVC tho I didn't used the strong fundamentals of the topic nor a framework, I separated the Logic, Rules and Design concerns by my own.
Unfortunately, I wound up with some issues similar to which is the right way to do the things, how this should be implemented, etc...
I end up needing to template the HTML, however, since I've used HTML as HTML itself, I end up updating/editing each and every affected file (for. eg. a web page header), unlike when I used PHP before, literally a file with a .php extension, where I can fully utilize templating, however, i read somewhere that it is not a good practice because it breaks the HTML.. so which one should I follow and how can I solve my problem, should I move to .php and then create a template page, or is there a way I could do such with HTML? if there is any, how can it be done?
Please for the meantime, don't point me to frameworks available, I want to understand basic things first before studying frameworks...
Anyone, please...
Edit...
so this is just fine and that it doesn't have any drawbacks...
main.php
<?php php stuffs ?>
<html>
<body>
HTML stuffs and some <?php php stuffs ?>
</body>
</html>
HTML has no templating capability.
It has frames and iframes, but they come with significant drawbacks and only provide include functionality.
You should use a proper templating language. This can run on the client, server or build system.
I'd recommend against running it on the client. It adds an unnecessary dependency that your visitors (including search engine indexers) have to fulfil.
PHP will do the job (it straddles the border of being a programming language and a templating language). My personal preference is for Template-Toolkit.
TT can run in your build system via the ttree utility, or you can run it on your server. There is a tutorial covering how to build websites using it.
If, and when, you move to building websites with more demanding server side requirements, then you can continue to use TT as it is supported but most of the web frameworks in Perl land (e.g. the dancer module for TT and the catalyst module for TT. Note that those links go to the hardcode documentation for the modules, and if you plan to use one of the frameworks you should start with a higher level tutorial)
HTML is a markup language - in other words it can mark up text to display to the user.
It cannot do any of the dynamic type functions you might need in a web application - like updating the date, for example.
So it is best to think of HTML documents, just like you might think of a Word document, a load of text that is displayed to the user.
As soon as you want to start using templates to display dynamic information (stuff from a database, maybe), you're going to need a scripting language. PHP is good for this.
I've had good experience with Smarty - a php templating engine.
On a side note, learning a framework can be a really useful part of the learning the basics. Most frameworks force you to do things in a good way, and sometimes the things they make you write in your code may seem a bit strange or illogical, suddenly one day the penny will drop and you'll realise why what you've been forced to do is sound from an engineering point of view.
You can look # javascript templating. I suggest you to give a try to http://mustache.github.com/
Modest is a template system that's supposed to look and feel like HTML.
The most common way to do HTML templating with PHP, is to use one of these popular templating engines :
Smarty
Twig
Latte
Mustache
Alternatively, you can just put placeholders in your HTML that look something like <% variablename %>. Just load your HTML, do a regex do find all placeholders and replace them with the corresponding variables.
Alternatively, you can load your HTML, parse it as a DOM document and then modify your DOM. I created the library DOM Query to be able to do this with a jQuery-like syntax, but you could use vanilla PHP or one of several other libraries as well.
Alternatively, you can do some HTML templating in frontend with JavaScript. If you want to do HTML templating both on frontend and backend, you might want to consider using Mustache, because Mustache templates can be used both in frontend (with JavaScript) and in backend (with PHP).

how to isolate the style (css+html) from php

how can i isolate the style (css+html) from php, like put in the php file just some lines including by it the whole style or theme.
ex:
echo
eval_template("header") .
eval_template("body") .
eval_template("footer")
So in future i can change the whole style without touch the php files
any idea ?
there are many ways how you could do this...
Here's a tutorial on templating in plain PHP
http://www.phpro.org/tutorials/Introduction-to-PHP-templating.html
You can also take a look at the many template engines out there.
twig is one of them: http://twig.sensiolabs.org/
Personally, I enjoy to do it manually.
PHP should not return both css and html code, or even better, it shoukd not return client-side code at all but rather dependencies to specific parts. You never want to modify a file that contains a lot of different things.
To separate css+html from the php code, what I usually do is a hierarchy done with include("..."); and include_once("..."). For example : include_once("header.php") > include("menu.php") > html semantic with css classes correctly initialized according to current context.
Then you import your css / js external scripts in header.php so that you never have to modify the whole thing unless everything changes or if you have a complete feature to add to the website. Same is possible for every sections of the website.
Hope this helps, for me it is incredibly reducing debug-time since everything important has to be done only once, then at the top of it, you can seperate as you wish.
There are a lot of template engines you can use to do that, i prefer use twig, that is integrated with symfony2 framework.
Twig is wonderful because is very easy to use and very flexible, you can use inheritance to create a common layout which can be extended and overwriten in some some part using special tags. This is a guide i've find on Symfony website but is very usefull to understand the logic behind twig: http://symfony.com/doc/current/book/templating.html

What templating languages are suitable for JS and PHP?

I'm looking for a templating "language" that works for both PHP and JS. I had a look at Mustache (has a very limited "if") and a few other like jquery-tmpl-php. So far but none of these seem to fulfil all my criteria:
Works with data provided by JSON (array, map, literal)
Has an "if" statement that can at least check if
a key in a map exists
a list element is first/last/odd/even
a value is equal to a literal
Can iterate over a list (iterating over keys in a map would be a bonus)
The same template and data generates exactly the same result with PHP and JS
Fast enough (I know, it's a bit vague)
Preferably no compiling step
Bonus: a nice way to "pluralize" texts and basically everything that makes i18n easier
Not smarty :)
I appreciate any ideas, suggestions or tips
Thanks,
Marek
I just wrote this whole post up only to re-read your question and see "not Smarty" :P . I'll just say I looked around for a while for a JS and PHP template library and Smarty seemed like the best option for me. You say Mustache is not enough. The only other one that comes to mind with both JS and PHP functionality is Haml.
Original:
I don't have a ton of experience with this yet but I've started using Smarty PHP templates. I create one Smarty template and send JSON to the client for Ajax requests. I then use this JS Smarty engine for client-side processing. If the client does not support Javascript, I can gracefully degrade by just sending the PHP associated array to the Smarty renderer server-side rather than sending it to the JSON parser. Still uses same .smarty file, working fairly well so far and I think I'm going to keep using this methodology for the rest of my project.

Interchangability of PHP and JavaScript templates (prevent duplication)

I use a MVC PHP framework to keep my web applications as DRY as possible. All of my HTML templates are neatly tucked away in one folder in the application scope of my project.
The problem is that whenever I use a JSON string to build a page with AJAX, I need to reuse a lot of lines from these templates and copy them somewhere in my JavaScript files. This means there is code duplication between templates in my JavaScript files and templates in my PHP application.
I was wondering how this duplication can be prevented. One way is of course to load the template using AJAX, but then I would end up with a double AJAX request for one page. Furthermore, the PHP templates uses different tag styles to represent variables than MooTools, but the HTML setup is the same.
So to summarize: is there any neat way or a tool to prevent duplication of templates so one file could be used in both PHP and JavaScript? For the record: I use the MooTools framework to build my JavaScript files.
Edit
After some research, I found the best answer yet in my opinion. For those who are interested:
PURE
PURE separates HTML representation and JavaScript logic completely so you don't have to bother including HTML elements in your scripts. The template can simply be provided in the HTML file itself.
Example:
// JSON string
{ 'who': 'me' }
// In your rendered HTML page:
<div id="who"></div>
// After the JSON string is sent back
<div id="who">me</div>
Furthermore, it can be used by a wide selection of libraries: MooTools, jQuery, dojo, Prototype etc.
Interesting question that I'm struggling with sometimes too.
you can put your html in your javascript code, which is duplicating and which you want to avoid
you can load your html with a separate ajax call, which causes more ajax calls to be run, and possible slowing down of your app. you may want to avoid it.
you can pass your html within the Ajax call that will load the data. That way, you only have one call. Let your PHP open your templates, and add them to the data-json stream.
you can put the template inside your original html, put it as hidden.
I'd go for solution 3, or possibly 4 if templates are small and limited.
The JSon would then be something like {"data": ... your original data object, "templates":{...}}
You might be looking for a template langugage that is available for multiple languages so you can re-use your templates across language boundaries.
One such template language is {{mustache}}, works in both PHP and Javascript and many more languages.

advice on php parsing

I am using phpTumblr, a wrapper around the tumblr blog api that allows you to access posts via php.
I want the site to display new posts dynamically, so I am using php to write html code. I find myself writing things like print(blablabla); or print(); ... and so on, and setting the header of the document to text/html, so that the browser would read it as html.
This just seems to me like a kind of ugly hack, and I was wondering if most dynamic pages are set up in this way, or are there different ways to convert php objects(say arrays) automatically into html tags. So far it doesnt seem like there are any.) maybe i have to be using some CMS software?
Any advice would be great.
Thanks
I believe what you're describing is known as a template engine. It essentially separates the logic from the UI, and allows you to write dynamic pages without an excessive number of print or echo statements.
For PHP, I would recommend Smarty, but Google can also help you with finding alternative ones if you find you don't like it.
PHP is a language in which you can do alot of different things and one of them is to send output to browsers. So if you want to print an array as HTML code , write a PHP function for it. PHP has NOTHING to do with HTML tags directly.
Like the above post mentions you can use Smarty templating engine ... BUT then you will need to learn the smarty language to print the array :)
All scripting languages work in this way. So lets say if any xyz language supports a function called print_array_as_html($array) .... then observe that it is a function. That's the idea of having functions/methods in a language , extend the functionality to get what you need.

Categories