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
Related
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 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
I've been on a project with a buddy who is leading us with Middleman. We are coding in HAML and SASS and he's obviously a Ruby Dev. I'd like to know if there's ANY type of equivalent for PHP? I'm going to eventually lead a team and I'm much more comfortable with PHP than Ruby.
I'd like to have a layout file (like Zend's layout file)
I'd like to...at one command, convert all of the source files from PHP to static HTML and place those static files in a 'build' folder so we can hand it over to the client.
Anyone know of some cool things out there to make this happen? Thanks a bunch!
A project I work on, www.findbigmail.com, was written completely in PHP to start with and then I did some Ruby/Rails work for a different project, and coming back to PHP was a grind. After using HAML, SCSS and other wonderful things like CSS and JS minify, oh and Compass to build sprites, it was painful to go back to PHP and work again in PHP files with embedded HTML etc.
So, driven by pure slothfulness, I looked around and found MiddleManApp (MM) - after a couple of side trips along the way.
Now we have a very strong separation between what is now a mostly static html site built by MM, with some PHP files that are POSTed to and then redirect back to html pages. Where we need more dynamic behaviour, we've added javascript to the pages and have them call PHP API wrappers around our pre-existing code.
Our site performance has jumped hugely (doh, now its all static html), and its poised to take another jump when the next MiddleMan version comes out with its improved cache-busting abilities inherited from the Rails 3.1 asset pipeline. E.g. we'll be able to reference main.css in our source scripts (which itself is made up of sub-scss files like _index.scss, _pricing.scss) and it will be built with references to main-2348jlk23489kdj.css -- allowing us to set the server to cache for a year and/or deploy many more files to CDN.
Our engineering performance is way up too. We're no longer reluctant to touch UI code for fear of introducing a syntax error into the PHP code. And no more mismatched HTML tags to cause grief. The other PHP developer wasn't familiar with the Ruby/Rails derived toolchain, but has quickly become proficient (though he is a rockstar developer, so that's not too surprising!)
Coming soon is i18n support. Most of that is in MM already and hopefully Javascript support
real-soon-now.
We also explored generating pages from HAML with PHP added to them. We decided it was probably quite simple - e.g. add a ":php" tag to the HAML pipeline and then use .php partials as needed. But, we found that between Javascript and wrapping the existing PHP code as an "engine API", we were able to keep the codebases neatly separated -- which we found we prefer overall.
I hope this helps! Happy to explain more.
There is one for PHP called Piecrust.
I ended up choosing Middleman for the bundled coffeescript, sass, etc., but Piecrust is well done.
http://bolt80.com/piecrust/
PHP can render static HTML from PHP code quite easily:
Easiest way to convert a PHP page to static HTML page
Generate HTML Static Pages from Dynamic Php Pages
PHP - How to programmatically bake out static HTML file?
You could wire up something with existing template systems like Twig or use PHP Markdown to more or less mimic what Middleman is doing and create static HTML pages from your source files.
EDIT: As Hari K T mentioned above, http://www.phrozn.info/en/ does exactly this.
I have some random HTML layouts that contain important text I would like to extract. I cannot just strip_tags() as that will leave a bunch of extra junk from the sidebar/footer/header/etc.
I found a method built in Python and I was wondering if there is anything like this in PHP.
The concept is rather simple: use
information about the density of text
vs. HTML code to work out if a line of
text is worth outputting. (This isn’t
a novel idea, but it works!) The basic
process works as follows:
Parse the HTML code and keep track of the number of bytes processed.
Store the text output on a per-line, or per-paragraph basis.
Associate with each text line the number of bytes of HTML required to
describe it.
Compute the text density of each line by calculating the ratio of text
t> o bytes.
Then decide if the line is part of the content by using a neural network.
You can get pretty good results just
by checking if the line’s density is
above a fixed threshold (or the
average), but the system makes fewer
mistakes if you use machine learning -
not to mention that it’s easier to
implement!
Update: I started a bounty for an answer that could pull main content from a random HTML template. Since I can't share the documents I will be using - just pick any random blog sites and try to extract the body text from the layout. Remember that the header, sidebar(s), and footer may contain text also. See the link above for ideas.
phpQuery is a server-side, chainable, CSS3 selector driven Document Object Model (DOM) API based on jQuery JavaScript Library.
UPDATE 2
DEMO: http://so.lucafilosofi.com/find-important-text-in-arbitrary-html-using-php/
tested on a casual blogs list taken from Technorati Top 100 and Best Blogs of 2010
many blogs make use of CMS;
blogs html structure is the same almost the time.
avoid common selectors like #sidebar, #header, #footer, #comments, etc..
avoid any widget by tag name script, iframe
clear well know content like:
/\d+\scomment(?:[s])/im
/(read the rest|read more).*/im
/(?:.*(?:by|post|submitt?)(?:ed)?.*\s(at|am|pm))/im
/[^a-z0-9]+/im
search for well know classes and ids:
typepad.com .entry-content
wordpress.org .post-entry .entry .post
movabletype.com .post
blogger.com .post-body .entry-content
drupal.com .content
tumblr.com .post
squarespace.com .journal-entry-text
expressionengine.com .entry
gawker.com .post-body
Ref: The blog platforms of choice among the top 100 blogs
$selectors = array('.post-body','.post','.journal-entry-text','.entry-content','.content');
$doc = phpQuery::newDocumentFile('http://blog.com')->find($selectors)->children('p,div');
search based on common html structure that look like this:
<div>
<h1|h2|h3|h4|a />
<p|div />
</div>
$doc = phpQuery::newDocumentFile('http://blog.com')->find('h1,h2,h3,h4')->parent()->children('p,div');
Domdocument can be used to parse html documents, which can then be queried through PHP.
Edit: wikied
I worked on a similar project a while back. It's not as complex as the Python script but it will do a good job. Check out the Simple HTML PHP Parser
http://simplehtmldom.sourceforge.net/
Depending on your HTML structure and if you have id's or classes in place you can get a little complicated and use preg_match() to specifically get any information between a certain start and end tag. This means that you should know how to write regular expressions.
You can also look into a browser emulation PHP class. I've done this for page scraping and it works well enough depending on how well formatted the DOM is. I personally like SimpleBrowser
http://www.simpletest.org/api/SimpleTest/WebTester/SimpleBrowser.html
I have developed a HTML parser and filter PHP package that can be used for that purpose.
It consists of a set of classes that can be chained together to perform a series of parsing, filtering and transformation operations in HTML/XML code.
It was meant to deal with real world pages, so it can deal with malformed tag and data structures, so it can preserve as much as the original document as possible.
One of the filter classes it comes with can do DTD validation. Another can discard insecure HTML tags and CSS to prevent XSS attacks. Another can simply extract all document links.
All those filter classes are optional. You can chain them together the way you want, if you need any at all.
So, to solve your problem, I do not think there is already a specific solution for that in PHP anywhere, but a special filter class could be developed for it. Take a look at the package. It is thoroughly documented.
If you need help, just check my profile and mail me and I may even develop the filter that does exactly what you need, eventually inspired in any solutions that exist for other languages.
I learned PHP by hacking away at phpBB2, even submitting a few mods to their database, which others downloaded and used. (I don't believe phpBB2 is supported any more with phpBB3 out so long now, so the v2 mods database is no more.)
One of my favorite things about phpBB was their templates system, which let the editor completely separate the HTML and the PHP. PHP files contained PHP: logic, database queries, and activating the templates. TPL files contained templates: HTML, template variables, and specialized HTML comments to allow for conditional or repeating blocks.
However, any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed). phpBB is the only PHP I've looked at which actually separates the language and the markup language, suggesting to me that few, if any, other PHP codebases do such a thing.
I'm looking to start working with some PHP again, but this time it won't be a phpBB forum, and it will be on a team. Based on my experience, separation of PHP and HTML is uncommon (please correct me if I'm wrong on this!). However, I'm so used to that dividing line, I hate reading mixed PHP and HTML.
In the "real world" of PHP programming, what's the preferred method:
PHP files with strings of HTML
HTML files broken up with PHP blocks
PHP and HTML completely separate (I wish?)
Something else?
If you want to separate the PHP from the HTML you can use a template engine (Like smarty http://www.smarty.net/).
Personally, I see no reason to add a template system/language into the mix, when PHP is already a prefectly good solution.
My preferred approach is to separate the display from the logic of the application. This could take the form of a full blown MVC framework. However, it could also be a simple matter of how you go about writing your code.
Expansion:
Ever since making the mistake of interspersing my HTML with copious amounts of ASP code, I have tried to separate page logic from display. Within a single page, this means placing all of the page logic at the top, storing the information to be displayed in variables and then echoing them out within the HTML at the bottom of the PHP file. The only logic which appears in the HTML portion is display logic. In other words, simple error handling, ifs, loops, etc. Basically, the same stuff that you'll find in most templating languages.
My reason for avoiding templating languages is that it's yet another form of syntax that I need to worry about. What's the point? PHP provides more than I need for this purpose.
Meanwhile, you can take a simple MVC approach by separating things:
controller.php
<?php
// some application logic
$data['message'] = 'Hello, World.';
include 'view.php';
exit;
?>
view.php:
<html>
<head>
<title>
A simple 'MVC' view
</title>
</head>
<body>
<p>
<?php
echo $data['message'];
?>
</p>
</body>
</html>
This isn't without its drawbacks and issues. However, if you think you can have complete, clean separation between application logic and display, you're mistaken.
We use a customized code igniter base for MVC and just have logic and layout separated. that doesn't necessarily mean there's no php in our html, just that its not used for logic. It's perfectly okay to loop through a recordset with php code in a template imho, just don't try to talk to business objects and actually do stuff in the layout templates. You could ofcourse also look into something like tal or a million others for the templates if you really want to get rid of all php code there. I'm kinda thinking that's mostly overkill though, unless "insert special circumstance here"
edit fixed typo
In my experience, a lot of PHP development, whether for better or worse, ends up being php files connected to each other through includes that print out snippets of HTML as needed.
Mind though, most of my PHP experience is for more of a "we just need something that works" solution than a "we need the most elegant and efficient solution"
any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed).
Yeah, the general quality of code out there is embarrassing.
Whilst you can go to a full-blown templating engine of your own, that may be overkill and in many cases the limited domain-specific-languages they provide will get in your way, when you could just be writing presentation logic in PHP.
If you want to still be writing normal PHP, but without the spaghetti:
Keep action code at the top of the file or in a different file. Put only application logic here, not any kind of HTML or templating. Any information generated in this stage that needs to be displayed by the template needs to go in a variable to be passed to the templating part, not printed out in the middle of a load of business logic.
Take your knowledge of tag-based templating and apply it to PHP. Have a single, correctly-indented hierarchy of code for both HTML and PHP presentation logic, as if you were writing ‘well-formed’ XML (whether or not you're actually using XHTML). Avoid putting HTML in strings at all costs.
Define an easier way of calling htmlspecialchars(), because otherwise typing that all the time is going to be a real pain, and if you aren't typing it all the time you're going to have potentially security-sensitive errors.
To summarise, eg.:
<?php
// active code here
// do things
// put any errors in a $errors array
// this trivial function would presumably be in an include
//
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
?>
<body>
<?php if (count($errors)!=0) { ?>
<ul id="errors">
<?php foreach ($errors as $error) { ?>
<?php h($error); ?>
<?php } ?>
</ul>
<?php } ?>
...
</body>
In the "real world" of PHP programming, what's the preferred method:
Oh, in the real world of PHP programming, the average project has a mishmash of approaches thrown together without any thought. In the real world the code is unmaintainable, bug-ridden, and insecure. You don't want to look at the Industry Standard, because the Industry Standard is to be broken in every way.
I prefer to use a template system to minimize the amount of PHP code contained in the HTML files. I really don't see any way to entirely separate PHP from HTML, but I feel that it is sufficient to separate business logic (database) from presentation logic.
My template system is home-baked, but I'm sure you can find a variety that would work by preforming a google search.
Based on my experience, separation of PHP and HTML is uncommon
True. But lot of PHP code is written by inexperienced developers. Further, PHP does not encourage, but rather discourage writing good code, and the ability to mix HTML with programming code is one of the examples of this.
If you expect to do high quality code, to be able to easily maintain and extend it, I highly recommend using template engine or something similar. Mixing both has a huge impact on the readability of your code, and will result in something becoming worse and worse over time. Refactoring will be painful, if not impossible.
Now, you have a large choice of the way to separate HTML from PHP
The most obvious one is to use an existing layout engine. There are plenty of them, some very well done and with a very low performance impact.
You can also write your own engine. It may not be a good idea on a big project (why reinvent the wheel?), but can be a solution either on a tiny project or when you need something very specific.
The last way I use in most projects is to build XML from business layer (XML serialization is quite easy in PHP), then to use XSLT to transform this to HTML page. It enables to do websites which are much easier to maintain and more easy to understand, and, by the way, enables to access the website data programmatically (loading XML instead of HTML page) when need. On the other hand, it decreases performance hugely, so is not intended for large websites with thousands of queries per second.
Most code starts with PHP and HTML strings, then evolves into a templating system during a big rewrite. Separating content from logic up front requires design, planning and communication among the team. Using XML or JSON instead of PHP arrays as the data format makes this easier.
you can mix up PHP inside HTML or vice versa simply by adding opening <?php and closing ?> PHP tags between your HTML.
<!DOCTYPE html>
<head>
<title>Hello world as text</title>
</head>
<body>
<?php
echo "<p>Hello world</p>";
?>
</body>
</html>
For more details : https://stackhowto.com/how-to-combine-html-and-php/