I was using phtml files in zend framework. Now I am using .tpl files.
I found how to use html script and all. But when I want to use php code. Then I'm using:
<?php
echo "test";
echo $this->content;
?>
The problem with this is it is in layout.tpl file. Main content is in index.tpl of other module.
Rather than fetching the content of index file It echoing just 'test'.How to make it works?
Edited: I also tried {$this->content}.
If you are using the Smarty Templating Engine and the SmartyModule, then you will have to use Smarty syntax in your view scripts, since the Zend\View\Renderer\PhpRenderer will be overridden by the Smarty Renderer (and the Smarty Templating Engine). Also, if you wish to use layouts with Smarty, please see Smarty's Template Inheritance mechanism. Here is an example:
layout.tpl
<html>
<head>
<title>{block name=title}Default Page Title{/block}</title>
</head>
<body>
{block name=body}{/block}
</body>
</html>
mypage.tpl
{extends file="layout.tpl"}
{block name=title}My Page Title{/block}
{block name=body}My HTML Page Body goes here{/block}
Otherwise, if you are using the PhpRenderer, it will not "recognize" any templating language, even if you change the view script's file extension to .tpl, since it will simply include the content of the view scripts (see lines 502-503 of the renderer's source code). Therefore, as with any include, the PHP code will be executed immediately and stored in the renderer's $__content property. This is probably the reason why your echo command is immediately executed.
So, basically, you will have to choose your renderer (PhpRenderer or Smarty Renderer through the SmartyModule) and then abide by its inner workings (PHP/HTML or Smarty syntax (ex. variables), respectively).
Related
I am looking to implement varnish into a data heavy/user-centric website. How do I setup ESI using a system which uses php to include html templates?
I currently use a custom php templating system (similar to an MVC design pattern) which works like this:
make page request -> php calculates logic -> php includes html template pages and fills out variables -> page is output
I've only ever seen esi tags used in predominantly html pages, to include php snippets.
like the code below:
<HTML>
<BODY>
The time is: <esi:include src="/php-includes/date.php"/>
at this very moment.
</BODY>
</HTML>
But can it be done the other way around? e.g. esi tags in php pages to include html snippets?
Similar to this:
<?php
//logic here
$content = "this will be displayed on the content page"
include("templates/header.html.php"); //esi would go here since page is static content
include("templates/content.html.php"); //no esi here, since page is dynamic content
include("templates/footer.html.php"); //esi would go here since page is static content
?>
You just have to create a kind of "ESI" renderer thingy for your specific MVC implementation, as in /esi.php?template=foo, then inside something like:
... whatever you need to boostrap your app in order to render a template ....
include("templates/$template.html.php");
.... exit so no header/fooder stuff is rendered, only template HTML of interest
Surely not as simple as that but in a nutshell a similar thing.
I would then put some logic atop each template file to emit either the HTML (if rendered by esi.php or if ESI "feature" is in disabled state) or <esi tag only.
So for example templates/header.html.php could have (pseudo-code):
if esi (detect by checking request_uri to be esi.php) then echo '<esi /esi.php?template=header?somevar-from-parent=...'; return
---existing code--
this is my first time making a component for Joomla 3.
I'm trying to convert a php website to a component.
Almost every view of my php website is built this way:
Header
Sidebar
Navigation bar
Actual content
Footer
Scripts
So basically it looks like this:
A view from php website
<?php require_once('includes/header.php'); ?>
<body>
<div">
<?php require_once('includes/sidebar.php') ?>
<div>
<?php require_once('includes/navbar.php') ?>
</div>
<div>
<!-- Content or something -->
</div>
<?php require_once('includes/footer.php') ?>
</div>
<?php require_once('includes/scripts.php') ?>
<script>
</script>
</body>
</html>
But in Joomla this is not possible. If I try to include or require a php file like above it just doesn't work.
View in component looks like this:
com_component
../views
../tmpl
default.php
view.html.php
../includes
header.php
footer.php
sidebar.php
scripts.php
navbar.php
Default.php is supposed to show a dashboard on the frontend.
This is what I'm trying to do in default.php:
Default.php
<?php include_once('../../includes/header.php') ?>
<body>
<?php include_once('../../includes/sidebar.php') ?>
<?php include_once('../../includes/navbar.php') ?>
<!-- Some content-->
<?php include_once('../../includes/footer.php') ?>
<!-- etc -->
What I've done
I've found some JDocument and JHTML functions which can add stylesheets and javascript to the template. But that is not what I'm looking for.
I used Joomla's addCustomTag function but it only shows a commented php line in the template.
Tried to make a String of it and passed it through a variable.
Questions
Is it possible to include php files in a template (default.php)?
If not, is there any other way to do it?
If yes, is that good practice in Joomla?
Thanks
To include files in the same directory as the given file, you can use:
include __DIR__ . '/../includes/header.php'
If you don't use DIR the current path is related to the main page (index.php in the site root) and not to the layout (default.php).
A more Joomla compatible solution is to put all your "sub-layouts" in the same folder with a conventional naming like this:
com_component/
views/
myview/
view.html.php
tmpl/
default.php
default_header.php
default_footer.php
....
Then you can use in your main layout the following code:
echo $this->loadTemplate('header');
...
echo $this->loadTemplate('footer');
You don't need a component to do any of this. I mean you can
do this but it should only be as an intermediary step since Joomla is designed to make all this easier by having APIs to include modules which is basically what all your pieces are.
You'll notice that in the joomla template file there are places where module positions are loaded. These are things like menus, footers, sidebars etc.
Depending on what they are you should really make each of these subsections a module. In some cases you can probably use existing modules already in Joomla or make a "custom html" module if you are just loading some html. In other cases makin a joomla module is really easy, just a few files, and you can put your php code there, really to start you can put the whole thing in the tmpl/default.php for the module or you can split it between the helper and the layout.
You'll be much happier in the long run if you take advantage of using a CMS rather than fighting it.
Components are only for the "body" area, what you need to do is make a template and then the modules.
It seems F3 framework doesn't handle php function calls within a page? I have a php navigation bar, which is uniform site-wide. I call up my layout page in my controller class thus: Template::serve('layout.php'). In the layout page, I include the navigation bar thus: <F3:include href="navbar.php" />. Within the navbar (navigation) file, I call a utility function siteUrl which gets the absolute url to a resource e.g. css or .js file. This function is defined in an include file which I include as follows: require_once "lib/globals.php. Within the navbar.php, I use the siteUrl as follows for example:
<img id="logo" alt="logo" src="<?php echo siteUrl('small-logo.png') ?>" />
This doesn't seem to work. When I view the generated source of the page, the src section of the img tag is an empty string: "". However, when I call the navigation bar from other pages that are not using the F3 framework (i.e. pages that are not being routed by F3::route. Not all pages of the website are routed using F3), it works fine.
What could be the problem? How could I call a php function from within a php page that is being rendered using Template::serve? It seems the entire content between the <?php ?> tag is not being executed when the page is being served by F3. Echo statements are not being displayed. Thanks for responses.
Template::serve() does not allow PHP. It is a templating engine. There are things you can do. You can define a function using F3::set('sum',function($a,$b){return 1+2;}); and then reference that function in the template with {{#sum(1,2)}}. I would re-read the templating documentation on the fatfree site: http://bcosca.github.com/fatfree/#views-templates
Again, the reason PHP is not working is because you are using Template::serve() and are therefore using the templating features of Fatfree. If you want to use PHP, I believe you can use F3::render() instead and it will render the page, allowing PHP, but you will lose all the templating functionality.
you can use raw php within the template tokens wrapped by curly brakets like this:
<img id="logo" alt="logo" src="{{ siteUrl('small-logo.png') }}" />
it will echo it automatically.
but using F3::set('image.smallLogo',siteUrl('small-logo.png')) to define the image paths and grap them with a simple {{#image.smallLogo}} feels much better.
page moved:
Fat-Free Framework 3 Template Directives
Do you know of any site that can help me start with making template driven sites in PHP?
First off I'll go ahead and start out with Smarty, since I've used it quite a lot. Since this is a community wiki, feel free to plug in examples of your own templating engine should you choose.
Installing Smarty
Templating provides a great way of structuring your HTML and separating out your HTML content from your logic code. It also provides a way to organize individual components of your HTML page, so it's easier to manage, and is more re-usable.
To start, we'll take at showing a simple page with Smarty. First off you need to actually get Smarty. So we'll head down to the Smarty download page. As of this writing, the latest stable version is Smarty 3.0.7, so we'll go ahead and download that. Downloading the .tar.gz file or the .zip file is up to the system you have. For Windows and Mac users (most likely using MAMP or XAMPP), .zip is probably a good choice, though you can always get programs to handle .tar.gz files. Users with Linux or *BSD type systems can grab the .tar.gz version.
Now then, we extract the file and get the following directory layout:
COPYING.lib
demo/
libs/
|__ Smarty.class.php
|__ ... some other files and folders ...
README
SMARTY2_BC_NOTES
Now, Smarty.class.php is the main file we're going to include to use Smarty. It's located in the libs directory. As 'libs' is a pretty generic sounding name, we're going to copy this to our document root folder, and rename it to Smarty. Now our theoretical document root folder is currently empty, so it will end up looking like this:
Smarty/
|__ Smarty.class.php
|__ ... some other files and folders ...
A Simple Template
Now that Smarty is installed, we'll create a very basic template and php script to show how it works. First off, to keep things organized we'll make a templates folder to keep our templates in. Then we'll create a mypage.php file, and a mypage.tpl file in our templates folder:
mypage.php
templates/
|__ mypage.tpl
Smarty/
|__ Smarty.class.php
|__ ... some other files and folders ...
mypage.php
<?php
require_once('Smarty/Smarty.class.php');
$smarty = new Smarty();
$smarty->assign("MYVAR", "Hello World");
$smarty->display("templates/mypage.tpl");
?>
templates/mypage.tpl
<html>
<head>
<title>My Sample Page</title>
</head>
<body>
<h1>{$MYVAR}</h1>
</body>
</html>
Now if we navigate to mypage.php, for example http://localhost:8000/mypage.php, "Hello World" will be displayed in large bold text. So what happend? Let's step through the code:
require_once('Smarty/Smarty.class.php');
Here we include the main Smarty class. We need this for any and all Smarty functionality.
$smarty->assign("MYVAR", "Hello World");
You'll be using this a lot. The assign command takes a value, "Hello World" in this example, and assigns it to a name, "MYVAR". If you look at the template:
<h1>{$MYVAR}</h1>
You'll notice {$MYVAR}. The {}'s indicate to Smarty that it needs to evaluate the expression inside. This could be a command or simply a variable. It could produce output or simply set a variable value. In this case, it simply outputs the value of $MYVAR that we assigned.
$smarty->display("templates/mypage.tpl");
Finally, we tell Smarty to parse the template, then display it as if you had simply echo'ed out HTML in a PHP page. Fancy eh? Now, a lot of people will want to iterate through arrays (ie. a set of db results), so let's take a look at an example of how to achieve that.
Looping Through Arrays
First we'll make adjustments to our code. The new listings are as follows:
mypage.php
<?php
require_once('Smarty/Smarty.class.php');
$myarray = array(
"John",
"Jane",
"Henry",
"Nancy",
"Gorilla"
);
$smarty = new Smarty();
$smarty->assign("MYARRAY", $myarray);
$smarty->display("templates/mypage.tpl");
?>
templates/mypage.tpl
<html>
<head>
<title>My Sample Page</title>
</head>
<body>
<h1>Results</h1>
<ul>
{foreach $MYARRAY as $myvalue}
<li>{$myvalue}</li>
{/foreach}
</ul>
</body>
</html>
If you reload the page, you'll get something like this:
Now, there are only a few changes to note:
$smarty->assign("MYARRAY", $myarray);
Instead of a string value, we assigned a variable which holds an array. This was passed to Smarty which used the data in the {foreach} loop:
<ul>
{foreach $MYARRAY as $myvalue}
<li>{$myvalue}</li>
{/foreach}
</ul>
The foreach in Smarty is much like the foreach of PHP. In this case, Smarty takes the array that was assigned to $MYVALUE and loops through it, setting $myvalue to the result of the current loop value. From there we can use {$myvalue} to refer to each individual item. Now, let's say we want to make this unordered list a widget to reuse in other places. We can do that through using templates themselves as variables.
Template Modularization
HTML can get very long very quickly. Smarty helps manage this by letting you break out parts of the page into individual components. So what we'll do is take our unordered list and put it into a separate page. Our new code will look like this:
mypage.php
<?php
require_once('Smarty/Smarty.class.php');
$myarray = array(
"John",
"Jane",
"Henry",
"Nancy",
"Gorilla"
);
$smarty = new Smarty();
$smarty->assign("MYARRAY", $myarray);
$content = $smarty->fetch("templates/mycontent.tpl");
$smarty->assign("MYCONTENT", $content);
$smarty->display("templates/mypage.tpl");
?>
templates/mypage.tpl
<html>
<head>
<title>My Sample Page</title>
</head>
<body>
<h1>Results</h1>
{$MYCONTENT}
</body>
</html>
mycontent.tpl
<ul>
{foreach $MYARRAY as $myvalue}
<li>{$myvalue}</li>
{/foreach}
</ul>
The result we get is the same, however the backend is now more organized. We can now reuse this mycontent.tpl file in other pages if we want. Common usages of this organization is making header, footer, and other parts of the page individual templates. This lets you narrow down to relevant pieces.
So what happened on the backend? The important command to take note of here is:
$content = $smarty->fetch("templates/mycontent.tpl");
fetch() works like display, except that instead of outputting it right away, it returns the result as a string of the rendered HTML. Note that because $MYARRAY is used in the mycontent.tpl, we have to assign the array right before it, not right before the final display() call. This ordering is important!
Conclusion
This concludes the very basic introduction to Smarty, and using a templating engine to work with managing your content. The Smarty Documentation provides a great resource for seeing all that smarty is capable of. Be sure to look through all the available commands to make sure you're using it efficiently!
Smarty for PHP is an adequate templating system. You can try and use that, plus their documentation to help develop a template driven website.
Depending on your needs you can create your own templateing system with a couple of included files.
Symfony, in addition to being a good framework, offers Twig.
Most HTML in a large website is duplicated across pages (the header, footer, navigation menus, etc.). How do you design your code so that all this duplicate HTML is not actually duplicated in your code? For example, if I want to change my navigation links from a <ul> to a <ol>, I'd like to make that change in just one file.
Here's how I've seen one particular codebase handle this problem. The code for every page looks like this:
print_top_html();
/* all the code/HTML for this particular page */
print_bottom_html();
But I feel uncomfortable with this approach (partially because opening tags aren't in the same file as their closing tags).
Is there a better way?
I mostly work with PHP sites, but I'd be interested in hearing solutions for other languages (I'm not sure if this question is language-agnostic).
I'm not a php programmer, but I know we can use a templating system called Smarty that it works with templates(views), something like asp.net mvc does with Razor.
look here http://www.smarty.net/
One solution at least in the case of PHP (and other programming languages) is templates. Instead of having two functions like you have above it would instead be a mix of HTML and PHP like this.
<html>
<head>
<title><?php print $page_title ?></title>
<?php print $styles ?>
<?php print $scripts ?>
</head>
<body>
<div id="nav">
<?php print $nav ?>
</div>
<div id="content">
<?php print $content ?>
</div>
</body>
</html>
Each variable within this template would contain HTML that was produced by another template, HTML produced by a function, or also content from a database. There are a number of PHP template engines which operate in more or less this manner.
You create a template for HTML that you would generally use over and over again. Then to use it would be something like this.
<?php
$vars['nav'] = _generate_nav();
$vars['content'] = "This is the page content."
extract($vars); // Extracts variables from an array, see php.net docs
include 'page_template.php'; // Or whatever you want to name your template
It's a pretty flexible way of doing things and one which a lot of frameworks and content management systems use.
Here's a really, really simplified version of a common method.
layout.php
<html>
<body>
<?php echo $content; ?>
</body>
</html>
Then
whatever_page.php
<?php
$content = "Hello World";
include( 'layout.php' );
Sounds like you need to use include() or require()
<?php
include("header.inc.php");
output html code for page
include("footer.inc.php");
?>
The header and footer files can hold all the common HTML for the site.
You asked for how other languages handle this, and I didn't see anything other than PHP, so I encourage you to check out Rails. Rails convention is elegant, and reflects #codeincarnate 's version in PHP.
In the MVC framework, the current view is rendered inside of a controller-specific layout file that encapsulates the current method's corresponding view. It uses a "yield" method to identify a section where view content should be inserted. A common layout file looks like this:
<html>
<head>
<% #stylesheet and js includes %>
<body>
<div id="header">Header content, menus, etc…</div>
<%= yield %>
<div id="footer">Footer content</div>
</body>
</html>
This enables the application to have a different look and feel or different navigation based on the controller. In practice, I haven't used different layout files for each controller, but instead rely on the default layout, which is named "application".
However, let's say you had a company website, with separate controllers for "information", "blog", and "admin". You could then change the navigation for each in a clean and unobtrusive manner by handling the different layout views in their respective layout files that correspond to their controllers.
You can always set a custom layout in the controller method by stating:
render :layout => 'custom_layout'
There are also great helper methods built into Rails so you don't have to rely on $global variables in PHP to ensure your CSS and Javascript paths are correct depending on your development environment (dev, staging, prod…). The most common are:
#looks in public/stylesheets and assumes it's a css file
stylesheet_link_tag "filename_without_extension"
#looks in public/javascripts and assumes it's a js file
javascript_include_tag "jquery"
Of course, each of these sections could be expounded upon in much greater detail and this is just brushing the surface. Check out the following for more detail:
http://guides.rubyonrails.org/layouts_and_rendering.html
What you suggested works OK. As long as print_top_html and print_bottom_html stay in sync (and you can use automated tests to check this), then you never need to worry about them again, leaving you to focus on the real content of the site -- the stuff in the middle.
Alternatively, you can combine print_top_html and print_bottom_html into a single call, and send it HTML code (or a callback) to place in the middle.
I use the partials system of Zend_View (very similar to Rails). A partial is essentially a small HTML template that has its own variable scope. It can be called from inside views like:
<?php echo $this->partial('my_partial.phtml', array( 'var1' => $myvar ));
The variables that get passed into the construct get bound to local variables inside the partial itself. Very handy for re-use.
You can also render a partial from inside normal code, if you're writing a helper object where you have more complex logic than you'd normally feel comfortable putting in a view.
public function helperFunction()
{
// complex logic here
$html = $this->getView()->partial('my_partial.phtml', array('var1' => $myvar ));
return $html;
}
Then in your view
<?php echo $this->myHelper()->helperFunction(); ?>