PHP Templating in Laravel 4 - php

I just did a fresh install of laravel 4.1. I am not really a big fan of templating languages so I would just prefer to use regular php for the templating. However, I do like the idea of inheritance and sections that laravel provides. I have seen examples of using the sections like so:
<?php Section::start('content'); ?>
Test Content
<?php Section::stop(); ?>
However, when I try this on my install I am getting:
Class 'Section' not found
When I try doing it with the blade templates it works fine but not with a regular php template. I cannot find any documentation at all about just regular php templates, all I can find is documentation on blade. Is this not available in the new version or has it changed? Any links or help would be greatly appreciated as googling keeps coming up with results for how to use blade templates.

You are looking for View actually Illuminate/View/Environment.php:
<!-- layuts/mastrer.php -->
<body>
<?php echo View::yieldContent('content'); ?>
</body>
<!-- views/home/index.php -->
<?php View::startSection('content'); ?>
<?php echo 'Welcome ' . $name; ?>
<?php View::stopSection(); ?>
BaseController class:
protected $layout = 'layouts.master';
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
HomeController class:
public function ShowHome()
$this->layout->title = 'Laravel -> Lout';
$this->layout->content = View::make('home.index', ['name' => 'Sheikh Heera']);
}
But, if you use these functions then why not just use the blade ?

Related

Using class in smarty templates

I am migrating from clean php views to smarty, and I have a problem converting the following template into smarty:
<?php
use \framework\core;
?>
<h1><?= Core::translate('some string to translate'); ?></h1>
So I want to use some class that's loaded via autoloader, and then use its translate method. How can I do that in smarty?
This is how I did this same task in one of my older projects using Smarty API extension:
// register additional smarty modifiers for I18N
$this->smarty->register_block("translate", array($this, "smarty_i18n_translate"));
// better alias
$this->smarty->register_block("_", array($this, "smarty_i18n_translate"));
// translation function
public function smarty_i18n_translate($params, $content, &$smarty, &$repeat)
{
if (isset($content))
{
if (isset($params['resourceID']))
{
$resourceID = $params['resourceID'];
unset($params['resourceID']);
}
else
$resourceID = NULL;
// setting context vars if specified
foreach ($params as $key => $val)
{
$this->setContextVar($key, $val);
}
// Core::translate($content); ?
return $this->translate($content, $resourceID);
}
return '';
}
This allows writing in views (I used {? as smarty tag delimiter):
<span class="label">{?_?}Operation type{?/_?}:</span>
One note: this was for some pretty ancient version of Smarty, they may have changed details of API, but it seems register methods are still there.
Btw in the docs there is this same problem illustrated as example: http://www.smarty.net/docsv2/en/api.register.block.tpl
try this logic/way, hope you might get some idea..
<?php
$my_obj = new MyClass();
$smarty->left_delimeter('{{');
$smarty->right_delimeter('}}');
$smarty->assign('my_obj', $my_obj);
$smarty->display('your.html');
?>
Then on your html
<h1>{{ $my_obj->translate('some string to translate'); }}</h1>

Using Smarty 3.1 with Kohana 3.3

KSmarty is a Kohana module meant to integrate Smarty with Kohana. I'm trying to migrate my current project (already using Smarty) to using Kohana.
I'm trying to get KSmarty set up, but I'm having difficulties getting the templates to work. This is the "hello world" example from KSmarty:
application/classes/Controller/Welcome.php
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Welcome extends Controller_Template
{
public $template = 'welcome';
public function action_index()
{
// Assign a value to the variable 'intro'
$this->template->intro = 'Hello world!';
// Create a nested view by loading a different template
$this->template->content = View::factory('content');
}
}
// End Welcome
application/views/welcome.tpl
<html>
<body>
<h1>{$intro}</h1>
<p>
{$content}
</p>
</body>
</html>
application/views/content.tpl
Yes, this works!
However, for me, the controller/view combo does not work as expected. Here are the variants of action_index() that I've tried:
public function action_index()
{
echo 'foo';
}
// Output: foo
public function action_index()
{
// Assign a value to the variable 'intro'
$this->template->intro = 'Hello world!';
// Create a nested view by loading a different template
$this->template->content = View::factory('content');
}
// No output
// No error in apache log, php log, or kohana log
public function action_index()
{
Ksmarty::instance()->assign(array(
'intro' => 'Hello world!',
'content' => APPPATH.'/views/content.tpl'
// Note: also changed {$content} in template to {include $content}
));
Ksmarty::instance()->display(APPPATH.'/views/welcome.tpl');
}
// Expected HTML output
I could simply use Ksmarty::instance() like this and get my website working, but this isn't how the Kohana Views system was designed, and it feels like a kludge, especially since the KSmarty example matches up with Kohana's use of Views.
I'm pulling my hair out trying to pin this one down, which is impressive considering the amount of hair-pulling Kohana gave me on the initial install. What am I doing wrong?
Oh, I have make two changes to KSmarty to reach this point:
All instances of Kohana::config('smarty') replaced with Kohana::$config->load('smarty'); as far as I can tell, this is a matter of a version change in Kohana.
Commented out $s->security = Kohana::$config->load('smarty')->security;; as far as I can tell, this is a matter of a version change in Smarty, and KSmarty is configured to FALSE anyway.
Adding echo $this->template; to the end of the view works. It's not in the Kohana nor the KSmarty documentation/examples, but it's close enough to satisfy me. If anyone else ever comes up with an answer that solves the problem without echo, I'll mark that answer as accepted, but until that time, I have a solution.
<?php defined('SYSPATH') or die('No direct script access');
class Controller_Welcome extends Controller_Template
{
public $template = 'welcome';
public function action_index()
{
// Assign a value to the variable 'intro'
$this->template->intro = 'Hello world!';
// Create a nested view by loading a different template
$this->template->content = View::factory('content');
// Output the view
echo $this->template;
}
}
// End Welcome

Steps to create a widget on Yii?

I have the following code on a given view:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'home-newsletter-form',
'enableAjaxValidation' => false,
'enableClientValidation' => true,
));
echo $form->textField($newsletterSubscribeForm, 'email');
echo $form->error($newsletterSubscribeForm, 'email');
echo CHtml::link("subscribe", "#", array('class'=>'btSubscribe'));
$this->endWidget();
?>
It happens that I will need this on MORE then one view, so I find a widget a better option.
I wish however to place this on a separate file (on app/widgets/ folder), and called on each view.
Can anyone please be kind enough to tell me what steps should we follow in order to achieve that?
Widget is the best solution here, it will keep your code DRY (Don't Repeat Yourself - focus on re-usability) as well.
<?php
// protected/components/SubscriberFormWidget.php
class SubscriberFormWidget extends CWidget
{
/**
* #var CFormModel
*/
public $form;
public function run()
{
if (! $this->form instanceof CFormModel) {
throw new RuntimeException('No valid form available.');
}
$this->render('subscriberFormWidget', array('form'=>$this->form));
}
}
And the view:
<?php
// protected/components/views/subscriberFormWidget.php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'home-newsletter-form',
'enableAjaxValidation' => false,
'enableClientValidation' => true,
));
echo $form->textField($newsletterSubscribeForm, 'email');
echo $form->error($newsletterSubscribeForm, 'email');
echo CHtml::link("subscribe", "#", array('class'=>'btSubscribe'));
$this->endWidget();
sample usage inside any view
<?php $this->widget('SubscriberFormWidget', array(
'form' => $newsletterSubscribeForm
)); ?>
Creating a widget is very simple in Yii. It couldn't be better explained than in the following short official documentation section, Here.
I little emphasis as lots of people found this answer useful. The following words are at my own taste, how I prefer designing my Yii application building blocks: when building your widget class always bear in mind that a widget is a kind of a view in Yii (v1.x). Its not supposed to process stuff, to perform important business logic decisions. Rather, as a view it merely supposed to render stuff. The decision making code in it should be focused in finding out what to render. I used to design in the past widgets that included some AJAX processing. Today I think this is bad design. A widget should render stuff. Need an accompanying processing unit? I would pack it all in a module, with controllers, possibly model classes, and the widget as an extension in that module. Cest tout :-)
You are better of using partials views.
Like this:
<?php $this->renderPartial('//partials/_myview',
compact('model', 'dataProvider')
); ?>
that way you can reuse the code in other views.
Steps to create widget
<?php
//protected/components
class Categorywidget extends CWidget
{
public function init(){
}
public function run(){
$model=Category::model()->findAll(array("condition"=>"isactive=1"));
$listdata=CHtml::listData($model,"category_id","name");
$this->render("category/category",array('listdata'=>$listdata));
}
}
<?php
//protected/components/views
$count=count($listdata);
$div2=ceil($count/2)+1;
$i=0;
?>
<div class="categories">
<h5>Categories</h5>
<ul>
<?php foreach($listdata as $key=>$value) {
$i++;
if($div2==$i){ ?>
</ul><ul>
<?php } ?>
<li><?php echo $value; ?></li>
<?php } ?>
</ul>
</div>
It's easy to create a widget in Yii, Just follow the link. Create Yii Widget
In 2 minutes I've understand how widgets work in this very short tutorial:
How to create Breadcrumb widget

Best way to construct a website application in code igniter

How do people construct websites with cake/CI ect... for easy maintenance on the html?
I can put each of the sections in its own view file and make the website that way:
<div id="header"></div> <!-- header_view.php -->
<div id="content"> <!-- header_view.php -->
<div id="left_column"></div> <!-- page_x_view.php -->
<div id="center_column"></div> <!-- page_x_view.php -->
</div>
<div id="footer"></div> <!-- footer_view.php -->
But each page_x_view.php file would contain
<div id="left_column"><!-- Content --></div>
<div id="center_column"><!-- Content --></div>
And I'm duplicating these items through each of the files, so if I need to change the column structure then it is not easy.
Hopefully I am clear.
I have a controller caled MY_Controller which has a method that renders the complete page. I extend all my controllers from this main controller. HOw this helps? My main controllers takes a view and embedds it in the main content area of page and assembles a complete page. This controller takes header, footer, sidebar views and does all the mambo jumbo. Its very easy to develop such a system in CI. Some this call two step or multiple views. So if some random day I have to change layout of my page I just need to look at MY_Controller.
Cake on the other side uses layouts. I have done just one project in CakePHP so am not that expert but you can achieve the same effect in any framework. Here is how I do it in CI
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
log_message('debug', 'Controller Library '.__CLASS__ . ' ('. __FILE__ .') loaded.');
$this->properties['viewPath'] = $this->config->item('viewPath');
$this->setPageMetaData();
$this->setFavIcon();
}
public function render($viewData = null, $data=null)
{
$data = array(
'headerLayout' => $this->printHeaderLayout(array_merge($this->properties, (isset($data['headerLayout'])?$data['headerLayout']:array()))),
'leftLayout' => $this->printLeftLayout(array_merge($this->properties, (isset($data['leftLayout'])?$data['leftLayout']:array()))),
'rightLayout' => $this->printRightLayout(array_merge($this->properties, (isset($data['rightLayout'])?$data['rightLayout']:array()))),
'footerLayout' => $this->printFooterLayout(array_merge($this->properties, (isset($data['footerLayout'])?$data['footerLayout']:array()))),
'containerLayout' => $viewData,
);
this->load->view($this->properties['viewPath'].'layout/layout.php', $data);
}
public function setPageMetaData($pageMetaData=null)
{
$this->properties['pageTitle'] = isset($pageMetaData['pageTitle'])? $pageMetaData['pageTitle'] : $this->config->item('pageTitle');
$this->properties['pageKeywords'] = isset($pageMetaData['pageKeywords'])? $pageMetaData['pageKeywords'] : $this->config->item('pageKeywords');
$this->properties['pageDescription'] = isset($pageMetaData['pageDescription'])? $pageMetaData['pageDescription'] : $this->config->item('pageDescription');
}
public function setFavIcon($favIcon=null)
{
$this->properties['favIcon'] = (null !== $favIcon) ? $favIcon : $this->config->item('favIcon');
}
public function printHeaderLayout($data=null)
{
return ($this->load->view($this->properties['viewPath'].'layout/header', $data, true));
}
public function printFooterLayout($data=null)
{
return( $this->load->view($this->properties['viewPath'].'layout/footer', $data, true));
}
public function printLeftLayout($data=null)
{
return($this->load->view($this->properties['viewPath'].'layout/left', $data, true));
}
public function printRightLayout($data=null)
{
return($this->load->view($this->properties['viewPath'].'layout/right', $data, true));
}
}
Do note that this is not the exact code. I had to modify it for you, so do not blindly user it. If you know CI you will understand that I have setup paths to view in a config file. This helps me in setting up two totally different themes and use same controller. I can also add authentication layer which will based on user authentication/cookies can show a login or logout link in header. This is a template which I keep change and I extend all my controllers from MY_Controller and use in my controllers I simply do
$viewDataForForm = $this->load->view($this->properties['viewPath'].'homepage/some-form', array(), true);
$viewDataForContent = $this->load->view($this->properties['viewPath'].'homepage/some-content', array(), true);
$this->render($viewDataForForm.$viewDataForContent);
HTH!
Codeigniter and CakePHP take advantage of the Model View Controller configuration. They separate the database queries and data processing from the views. This provides an easy to use and easy to maintain way of coding. Multiply controllers can use the same view which helps cut down on the amount of code written and the complexity. Methods in the models can be reused which reduces bugs and amount of code written. And controllers provide and easy to follow way of reading and writing code. I am not sure if I answered your question but comment on my answer if you need and more explanation.

Do I need to hack ZendFramework1.10.8/Doctrine1.2.2 to get model generated?

I've started reading on zend framework and it's use with Doctrine and have implemented a small project to grasp the understanding.I've come to a point where i needed my model generated as in having a generate script like the one suggested in Doctrine 1.2.2 pdf manual.After few unsuccessful attempts like
Class 'sfYaml' not found in
G:\php_document\zendworkspace\BookingManager\library\doctrine\Doctrine\Parser\Yml.php
on line 80
i've googled and found out what people are doing about that.
To me it sounds too much the fact of having a command line script to do that work.So my question is do i really need the command line or i fail to load something is my application.ini file to get the error up there?
my testerController is like this:
class Testing_TesterController extends Zend_Controller_Action {
public function init(){
$optionDoctrine = Zend_Registry::get("config")->toArray();
$this->config = $optionDoctrine["doctrine"];
}
public function generateAction() {
$this->view->drop="dropping database............";
Doctrine_Core::dropDatabases();
$this->view->create = "creating database........";
Doctrine_Core::createDatabases();
$this->view->models = "generating models....";
//things started breadking from this line Doctrine_Core::generateModelsFromYaml("$this->config[yaml_schema_path]","$this->config[models_path]");
// $this->view->tables = "creating tables.......";
// Doctrine_Core::createTablesFromModels($this->config["models_path"]);
// $this->view->success = "tables and model successfully generated";
// $optionobject= Zend_Registry::get("config")->toArray();
// $this->view->generate =$optionobject["doctrine"]["yaml_schema_path"];
}
public function testAction(){
$dbs= Doctrine_Manager::connection()->import->listDatabases();
$this->view->test = $dbs;
//$this->view->test = "test";
}
}
the generate view is like this
<h1>My Manager:: generate page</h1><br>
<div style="text-align: left"><?php echo $this->drop; ?></div>
<div style="text-align: left"><?php echo $this->create; ?></div>
<div style="text-align: left"><?php var_dump($this->models); ?></div>
<div style="text-align: left"><?php echo $this->tables; ?></div>
here is my bootstrap class
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDoctrine(){
require_once 'doctrine/Doctrine.php';
$this->getApplication()->getAutoloader()->pushAutoloader(array('Doctrine','autoload'),"Doctrine");
//$this->getApplication()->getAutoloader()->pushAutoloader(array('Doctrine','modelsAutoload'),"Doctrine");
$manager = Doctrine_Manager::getInstance();
//$manager->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING,Doctrine_Core::MODEL_LOADING_AGGRESSIVE);
$manager->setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE,true);
$doctrineConfig = $this->getOption('doctrine');
$conn = Doctrine_Manager::connection($doctrineConfig['dsn'],'doctrine');
return $conn;
}
protected function _initDoctrineConfig(){
$conf = new Zend_Config($this->getOptions(),true);
Zend_Registry::set('config',$conf);
return $conf;
}
}
I've also adopted the use of modules which seems to complicate my situation so what do you think is the best to go with? thanks for reading
You need to grab the sfYaml component and install it. I Thought it was int the Doctrine svn repo as an svn:external but maybe not... you can get it from the Symfony components site.
Im not sure what tutorial youre following but if you drop:
http://svn.symfony-project.com/components/yaml/branches/1.0/
into your library folder as sfYaml and add library/sfYaml to the include path you should be fine assuming youve gotten everything else set up correctly.
Also whay is your command line script using Zend_Controller stuff? Shouldnt you be using the Zend_Tool_Framework infrastructure or writing a completely custom script? Thats how I've done it in the past anyway...

Categories