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.
Related
<div id='universals' data-path='/a/' data-load='1'></div>
This is a realy odd case. I have front-end code ( JavaScript ) which knows where it's resources are based upon a path I pass to it via PHP which writes the HTML above.
This is a cool feature that allows me to simply rename the root of my folder on the server and everything keeps working as PHP determines the current working directory and sends it to the client via the code above.
It is a form of reflection.
However I want to build this into an application framework on the front-end.
Now my javascript library, let's call it foo.js is dependent upon a dom element. I'm pretty sure this is not good practice.
My plan it to just make the id settable like this.
foo.setUniverisal('#universal');
and then put in the documentation which attributes are needed.
Any other ideas or better ways to eliminate any kind of dom dependency?
I think the best approach is the simplest one:
foo.setDataPath("pathToData")
Then your client-side "glue" code (one that puts together your library, HTML and PHP) will take a path from your tag and call foo.setDataPath. This will be the most orthogonal design (What is "Orthogonality"?).
Example of situation, where it might be relevant: what if this libary be initialized from the HTML, where this tag cannot be generated. For example, because HTML will be served statically (or via CDN).
I have a php file and a bunch of HTML elements that include:
header
css
a "spacer" element used repeatedly, static
a bunch of templates that will take arguments from the PHP code for what to insert
Basically I'm wondering what the right way to factor all these files in. I'm guessing I should have a file.css in my folder that the php will slurp up into memory and drop in the header information. Should the spacer element be saved as "spacer.html", and the PHP will slurp up one copy of it into a string and drop it into the HTML as necessary? Or should all of these just exist as string constants in the PHP?
It's a little trickier for the dynamic "template" elements because I'm not sure how to separate the HTML and let it have markers that the arguments get dropped into.
You should look into MVC. A popular one right now is CodeIgniter. The idea is you take those HTML "templates" and create (V)iews. PHP uses a (C)ontroller to direct the user and call on (M)odels to fetch data, then send the appropriate variables to the (V)iews for the browser.
I've noticed some of the other answerers (SP) mentioned MVC. MVC is incredibly important because it allows you to separate your business logic from your "view" display/UI layer and your database logic from your business logic.
Like, AlienWebguy, I'd recommend Code Igniter, but there are a number of other good frameworks out there for PHP.
As far as what it appears that you're asking is how you should structure both your view layer and business logic. If I have something common like a header and footer, I'll put them in
view/include/header.php
and
view/include/footer.php
The header file will generally contain the <html> tag, the style sheet link(s), any common javascript script files, and a common header (like the logo and navigation). The footer file will generally contain the copyright info, any footer links, and the </body></html>.
Generally what you should look to do in creating your views effectively is to have them process model objects to display the HTML, and generate absolutely no HTML in your controller layer. E.G.
<table>
<?php
foreach ($users as $user) {
printf('<tr><td>%s</td><td>%s</td></tr>', $user->id, $user->user_name);
}
?>
</table>
Doing that makes things a lot cleaner by avoiding interspersing concerns at the wrong "layer".
The other thing you can do, if you're not interested in writing straight PHP in your views, is you can use a templating engine. Code igniter includes support for (but you don't have to use) a template engine.
I usually suggest using some good ol' php includes to tackle this.
File structure wise, I'd probably have an index.php file -- which (without knowing much about your templates in #4) would outline the page. You could call in the header.html page or put the header right in the index.php file.
The css file would best be named: style.css (this is pretty standard) and you can call that from your header file.
Not sure if you're getting at this, but you can include HTML in a .php file. You'd just name the file something like: index.php and then your code can be:
<p>This is HTML.</p>
<?php echo("This is PHP."); ?>
And intermix them throughout.
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.
I am (mostly) a front-end developer working on a prototype with a backend guy on a site. The basics of it would require a user login area, as well as a search form that would search and return results from a database table.
He is doing the backend logic with Java and PostgreSQL. He proposes to return a JSON format to me upon a query. This means I will have to take the data from the JSON string and populate/create the HTML markup. I can do this with either Javascript, or PHP. It seems to be that PHP would be a no brainer as I don't need to create HTML markup with Javascript/jQuery and also all the data populated by the server already, reducing the load on the client side, but this means as a "front-end" person I am also writing PHP.
And regarding loading all server data onto a page with Javascript, is this standard practice? Or should it only be used on AJAX?
Should the backend guy be generating the markup as well? What's the best way of separating this frontend and backend work? THanks!
If you are using PHP, you are a backend-guy, too.
If the markup is generated by the server, than you would usually not write an AJAX-application, because the markup is generated by the server.
In fact if you want to write a ajax-application, you have to manipulte the DOM with Javascript. Use jQuery or something like that to do this.
Seperating frontend and backend is done by creating an Interface, a contract which will separate the UI from the Backend-Logic. In your case the contract is the format of your JSON Data.
A good compromise would be to do either:
Option 1
A small PHP script server-side which formats the restults into a table with appropriate Ids/similar to allow javascript to add classes for styling. This entire table could be returned via an AJAX call and placed within a placeholder div on the page.
Option 2
The server returns simple JSON to the front-end, the front-end uses whatever mechanism it sees fit to build the appropriate HTML
The first one is a little cleaner to code - The generation of the HTML is seperated from the styling, but it's an extra hop (the PHP) and is slightly inflexible - the JS can modify the table as appropriate but it's limited by the html PHP sends.
The second is slightly more verbose to code but completely flexible.
I send the data from the server to the browser in JSON all the time, format on the browser with templates of one form or another. I would rather work with arrays in Javascript as the array methods like map and filter make it much easier.
I have a medium size legacy php application with almost no javascript integration. I've recently been learning javascript (yes actually learning it) using Douglas Crockfords excellent book and taken YUI as my library of choice. I've tried out a few things and got a few things working but now I want to integrate the various components etc into my application properly, my question is how to go about doing this for ease of maintenance and code reuse.
Currently the application consists of
php pages
smarty templates (html templates with some special template markup) for each section of a page so multiple templates may be used for a single page.
single css file.
I have the following ideas about how to integrate my javascript into the pages.
Write inline javascript in each smarty template with the code required for that section.
Write a seperate .js file to go with each smarty template that is linked in and then a single inline script to run it.
a seperate .js file for each php page which would have all the functionality required for the entire .php page. A small inline function would call whatever functions were required.
Something I havent though of?
Does this make any sense? Does anyone have a good suggestion for this?
Update:
One extra bit of info is that its an internal application, so its not so important to restrict everything to a single file.
Two other options:
A single JS file that contains all the JS for your entire site. Depending on your caching settings, you should be able to get the user to download just one file for the entire site and use a cached version for every other page.
Divide your JS up according to function, rather than page, and include whatever functionality each page requires. E.g. one page may require tabs, form validation and animation, while another may only require tabs.
Or you can have a hybrid of these: one JS file that contains the vast majority of your code and an extra file if needed for particular pages or templates.
None of the approaches mentioned are wrong (though I'd skip the inline JS one as much as possible); which one is best will depend on your precise situation and your personal preferences.
Firstly, most setups allow a master layout template in which you can place a common page opening or, alternatively, each template includes some global header.
That being said, you should do a combination of 1, 2 and 3:
Have a .js that is included in all templates that contains global functionality. Each template may also optionally have it's own .js specific to that page or section of pages. Finally, if there's tiny amounts of code specific to a page (or must be dynamically generated each time), it won't make sense to initiate another http connection for it so have that source be right in the template.
if you don't have a ton of javascript then create an external js file and include it in the header of the webpages and be done with it.