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
Related
Why not just always use embed?
According to the docs the embed tag combines the behavior of the include and extend tags.
I understand that in a lot of cases you don't need to do extend and only want to render the contents of another template, but it seems to me like you could just always use embed and serve that purpose. Are there any performance ramifications of embed to be aware of? Any functionality differences I'm missing?
I would summarize the differences and similarities between Embed and Include as follow,
Both were added to twig to make HTML code snippets reusable.
Both are used for functional separation of templates (footer, header, ...)
Both are dynamic.
Include is used to wrap code that has non flexible HTML structure.
Embed allows flexibility.
Based on the differences, Include should be used only when you need to split a template into many functional sub-templates and reuse the wrapped code elsewhere.
While Embed is used when you need to customise the reusable templates.
So, it's more a matter of design than anything else (performance, code execution, ...)
Choose the helper that fit your needs.
As a small part of a university project I'm working on (custom MVC based project management system), I need to develop a template engine. I don't wish to use an off the self system such as Smarty because I've written every other part of the project myself and don't want to go back on that now.
Anyway, I've managed to code something simple so far, I have a class, create an instance of it, add some data to the instance, then pass in a template file. The file has a series of tags like {this} when then get replaced with the data. Simple.
The issue I'm having is when it comes to looping things - i.e. a table of users or a list of categories. At the moment I have a template file for the page (users.html) which contains the opening and closing tags, with a template tag between them called {users}. I then have another template file (users-detail.html) which displays a table row with the user info in. I'm creating a new instance of the users-detail.html template, adding the data, parsing it, then placing the output (string of HTML) into an array. I then loop this array, attach all the strings together, then assign this to the {users} tag in the users.html template file.
As you can probably tell from that explanation it is a bit of a bodge, and there are probably better methods out there for doing what I'm trying to achieve. Ideally I want to avoid using PHP in the template files if possible, and I often need to have multiple loops within one template file.
If anyone has any tips / advice on how I can achieve this, or any tutorials I could follow to get some inspiration that would be much appreciated.
Thanks in advance.
I've seen that approach before (including another template for the insides of loops). I used to work on an old version of vbulletin which does (or did) this. It makes things annoyingly complicated because you can't just add a loop to a template - without setting up a whole new template for each layer of looping.
I'd advise you instead to go along the route of Smarty.
Classically, this statement:
I don't wish to use an off the self system such as Smarty because I've written every other part of the project myself and don't want to go back on that now.
... indicates you really should just be using Smarty. In the real world that would be a poor justification for re-implementing something yourself. But I am like you, and I understand that you want to implement something yourself (because you want to learn, you find it fun, you are a perfectionist, etc). As long as you do it on your own time and it's a personal project, go for it.
It would be worth studying Smarty to see how it works (not just the syntax but how it compiles templates, stores the compiled version etc). Are you comfortable writing a tokeniser/parser in PHP which can compile your template language and output PHP? If you are advanced enough to do it, do it. At the very simplest, you read in a tag like {foreach from=$something} and somehow translate it to <?php foreach ($something as $thing) { ?>. You check token types, etc to make sure the template tag is valid, and so on.
I have started coding in clojure, and I'm really impressed by Enlive. One thing that I really like about it is that Enlive uses html-only templates. So a template is a file with html in it, ending in .html, simple as that. It gets parsed into a dom tree and then that dom tree is manipulated by clojure/enlive, combined, made dynamic, etc. No syntax in the html template files, a beautifully clean separation.
Another example of a similar system, done via javascript, is PURE.
Is there anything like that in php?
Or, in general, any ways of doing html-only templating?
Fascinated to hear of Enlive. I've been thinking about this concept for a few years and have hacked together something in PHP that shares some principles: templates are pure HTML, and you "fill" them by addressing content to a specific node in the document using CSS or XPath.
$t = new Template('yourfile.html');
$t->fill('#nav',$someMarkup);
$t->fill('#header',$otherMarkup);
I also experimented with throwing together some provisions for separating the content out into a "stylesheet" of sorts... well, "stylesheet" is the wrong word. I'm calling them content-addressing sheets (the project is called CAST, for content-addressed-style-templating). A CAS looks like you might expect:
.col #foot {
content: 'foot';
}
#content {
content: file_get_contents('pangolin.txt');
}
The values of content are assumed to be PHP expressions. There's some provision for setting up PHP that applies across selectors, too.
Take a run of the cssfill.php script that's in the tarball (best invocation is probably ./cssfill.php pangolin.cas pangolin.html, you might have to change the path to your php interpreter inside cssfill.php), take a look at the output, compare with the input files.
If this post generates any enthusiasm for the idea in you, feel free to let me know. I've been wondering whether this was a crazy idea or whether it has a place, if it does, I'd be happy to turn it into a thoughtfully released open source project as opposed to a tarball randomly tossed onto the internet.
You can check phptal.org. It's a template engine for PHP that uses HTML tags.
But it's not that fast.
You can also check other projects like twig-project.org witch is waaay faster.
Checkout PHPTAL.
PHPTAL is a XML/XHTML template library for PHP5 which provides compiled templates and fine-grained caching.
Templates are defined in pure XML/HTML markup.
<div class="item" tal:repeat="item itemsArray">
<span tal:condition="item/hasDate" tal:replace="item/getDate"/>
<a href="${item/getUrl}" tal:content="item/getTitle"/>
<p tal:content="value/getContent"/>
</div>
Interesting starts. But I'm impressed why we can't have diferent template with specimen text to change the view and the different state of elements - and extract the code to create exiting template systems or just fill it up with content. Find the workflow feels so broken an complicate - don't like mixing html with php / js nor writing abstract template systems. Need to much brain - to much commication without easy visualisations.
I think Psttt! templating engine for php is exactly what are you looking for, it keeps your html template intact allowing you to better reuse your htmls.
full source code here http://github.com/givanz/psttt
I have a web application developed using PHP. I want my users to select themes for their pages throughout the application.
Where should I start before using PHP themes?
What should I know about Themes in a PHP application?
Edit:
My question about themes is only about changing the color of the layout, not the images.
Suppose My ADMIN user will have white and Orange, but my staff user will have white and green...
How it can be done in PHP with CodeIgniter?
There are lots of directions you can go with this.
1) "CSS ZEN"
This is where the markup remains unchanged, but you totally change the design just by using CSS and images. Demonstrated very well on http://www.csszengarden.com/
2) MVC Stylee
This is where you create a model that represents the page data and then pass it to a view, which contains some inline echo statements. The idea is that you could send the same model to a totally different view so it could look entirely different, HTML and all. Cake PHP is a good start for this: http://cakephp.org/
Example:
<div class="content">
<? echo $Page->Content ?>
</div>
3) Micro-Markup
With this method, you add your own "special tags" to an HTML page. You then read in your plain HTML page and replace the special tags with the information you want to display. This is good if you want your templates to be recognisable to HTML guys that don't know PHP and might break the PHP code in the MVC app.
Example:
<div class="content">
<#Content#>
</div>
Out of all of these, MVC is a very structured way of achieving what you want - however, I listed the other options as they cater for specific scenarios that might be relevant to you.
I have implemented the concept in all three of these, in situations that were appropriate for each.
Regarding The Edit In The Question
I imagine you'll have "something" that represents your user - so it is as easy as:
(In the event of just wanting to override a few settings...)
<link href="style.css" type="text/css" rel="stylesheet">
<?php if ($User->Type === USER_ADMIN) { ?>
<link href="admin.css" type="text/css" rel="stylesheet">
<?php } ?>
You can adjust this example in the following ways:
Use a switch statement if there will be many user types
If the replacement is total, rather than just a few overrides, you may want to completely swap the stylesheet.
You would usually set up template files that contain the HTML and CSS, and build in the PHP generated values at runtime.
The best approach to this is to have the theme reside in a separate directory, containing no code, just template variables like {mainmenu}, {backbutton}, {content} ... you get my drift. Those are then filled by your PHP script, possibly with the help of a template engine like Smarty (No need to re-invent the wheel here).
There is also the approach of having PHP markup directly in the template file(s) like echo $xyz; while this is a perfectly valid practice I use myself often, I recommend using a template engine over using PHP markup in the code if you want a solid, future-proof templating system because:
First, there is less that a designer can break when working on the HTML.
Second, having PHP markup in the code is a temptation to program PHP logic inside the template (loops, conditions) instead of properly preparing them in the PHP code at the point where the template variables are created. That is terrible for maintenance and the further use of your templates, because you have to replicate that PHP soup into every new template again. After all, you want to have a template engine so others can create new looks for your product, without having to know how to program it.
Third, with the templating engine based approach you have the possibility to add caching where necessary without any additional work. Not possible with the scripting approach. Yes, in a web application you won't be able to cache that much, but with a lot of data, there will be instances where it will help the user experience.
Fourth and least important, it makes your template less easy to export to other applications, and import templates from other applications.
The CSS Zen approach mentioned by Sohnee is great for websites, but is going to be too limited for a web application that uses complex input elements, JS based menus, and the like. It is too often that those elements need to be changed and customized in the markup.
If you have a look at my CodeIgniter Template library it briefly explains how you can set up themes and layouts (the equivalent of header & footer).
If you set up global code such as a Hook or a MY_Controller then you can dynamically set your theme based on the logged in user, the user type, etc.
Eg:
if($user->role == 'admin')
{
$this->template->set_theme('admin_skin');
}
else
{
$this->template->set_theme($user->theme);
}
That is just a VERY basic example of the sort of thing you could use this Template library for.
CMS Solutions
Magento and Wordpress package all theme related files into their own seperate directories. These contain the serverside code, stylesheets, images and javaScript for the theme. The user in effect chooses a directory to use which affects how the page is layed out and styled.
An easier approach
A much easier way to get started would be to accept that the actual content, e.g. HTML of a page would stay the same, but let the user choose from various CSS style sheets.
When choosing a style sheet the system could use JavaScript to load it in dynamically so that the user can preview the look they are choosing.
If you have really good semantic HTML it will be enough to change the CSS files. Unless the design changes are really heavy. Then it would make sense to provide PHP templates that are build with some sort of modules: variables which contain certain HTML structure like navigation or sidebar, etc.
For themes you do not need PHP. Just define your themes in CSS (the best way is one file for each theme) and use a simple JavaScript chooser like at this site: http://www.fotokluburan.cz/switchcss.js.
I've been looking for some guidelines on how to layout PHP code. I've found some good references, such as the following:
http://www.dagbladet.no/development/phpcodingstandard/
and this question on SO.
However, none of that quite gets to what I'm specifically wondering about, which is the integration of HTML and PHP. For example:
Is it OK to have a PHP file that starts out with HTML tags and only has PHP inserted where needed? Or should you just have one section of PHP code that contains everything?
If you have a chunk of PHP code in the middle of which is a set of echo's that just output a fixed bit of HTML, is it better to break out of PHP and just put in the HTML directly?
Should functions all be defined in dedicated PHP files, or is it OK to define a bunch of functions at the top of a file and call them later on in that same file?
There are probably other questions I'd like to ask, but really I'm looking for someone to point me at some kind of resource online that offers guidance on the general idea of how HTML and PHP should be combined together.
Combining programming code and output data (including HTML) is IMHO a very bad idea. Most of the PHP gurus I know use a template engine such as Smarty to help keep the two things separate.
There's really not a single, common standard for these things. Most languages are more restrictive than PHP in this sense.
In the later years, a lot of so-called frameworks have emerged, and amongst other things they define a set of rules for everything from naming over where to place files and to which style your code should follow. There are several frameworks around, so you can't really pick one and call it the standard. However, most frameworks have a subset of commonality. For example, most follows some variant of the PEAR Coding Standards.
I usually try and follow the standards that are set by the language's core libraries.... oh wait.
Seriously through - you should try and follow the MVC pattern in any web application as it is pretty much standard practice regardless of language. In PHP this can be achieved in a quick-and-dirty way by treating index.php as your controller and separating data logic and presentation by file. This small step will at least let you move your code to a full featured framework when and if you choose.
Use a template engine when you can. If you haven't learned one, or don't want the overhead (which is minimal), use practices that cause you to have quick-and-dirty templating:
Functions that do not display anything have no place in a file that does display something.
Print variables, not HTML. Whenever outputting HTML, break out of the PHP and write HTML with print statements to handle any small details that are needed (actions for forms, IDs for controls, etc.).
Remember, when you include a file that breaks out of the PHP to print content, that will be treated the same as if you do it in the main file. So you can create simple templates that just included PHP files, and those files will print variables in the right places. Your index.php (or whatever) does all the real work, but all the display is done by the secondary "template".
Many PHP tutorials intermix logic and display code. It took me years to break the bad habits that encouraged in me. In my experience you can't separate things too much in PHP, and entropy will pull you towards intermixed code if you don't fight it.
Coding standards should be more than how to layout your syntax, but sadly that's what they tend to be in PHP.
FWIW, phc will pretty print your code in the Zend style.