Commit 739f3b13 by Alexander Makarov

Fixes #4553: Smarty enhancements

parent fcaddb0c
...@@ -106,9 +106,9 @@ Aliased class import: ...@@ -106,9 +106,9 @@ Aliased class import:
{{ use({'alias' => '/app/widgets/MyWidget'}) }} {{ use({'alias' => '/app/widgets/MyWidget'}) }}
``` ```
#### Referencing other views #### Referencing other templates
There are two ways of referencing views in `include` and `extends` statements: There are two ways of referencing templates in `include` and `extends` statements:
``` ```
{% include "comment.twig" %} {% include "comment.twig" %}
...@@ -118,8 +118,8 @@ There are two ways of referencing views in `include` and `extends` statements: ...@@ -118,8 +118,8 @@ There are two ways of referencing views in `include` and `extends` statements:
{% extends "@app/views/layouts/2columns.twig" %} {% extends "@app/views/layouts/2columns.twig" %}
``` ```
In the first case the view will be searched relatively to the path current view is in. For `comment.twig` and `post.twig` In the first case the view will be searched relatively to the current template path. For `comment.twig` and `post.twig`
that means these will be searched in the same directory as the view that's rendered currently. that means these will be searched in the same directory as the currently rendered template.
In the second case we're using path aliases. All the Yii aliases such as `@app` are available by default. In the second case we're using path aliases. All the Yii aliases such as `@app` are available by default.
...@@ -264,8 +264,9 @@ Then in the template you can apply filter using the following syntax: ...@@ -264,8 +264,9 @@ Then in the template you can apply filter using the following syntax:
Smarty Smarty
------ ------
To use Smarty, you need to create templates in files that have the `.tpl` extension (or use another file extension but configure the component accordingly). Unlike standard view files, when using Smarty you must include the extension in your `$this->render()` To use Smarty, you need to create templates in files that have the `.tpl` extension (or use another file extension but
or `$this->renderPartial()` controller calls: configure the component accordingly). Unlike standard view files, when using Smarty you must include the extension in
your `$this->render()` or `$this->renderPartial()` controller calls:
```php ```php
return $this->render('renderer.tpl', ['username' => 'Alex']); return $this->render('renderer.tpl', ['username' => 'Alex']);
...@@ -277,20 +278,173 @@ The best resource to learn Smarty template syntax is its official documentation ...@@ -277,20 +278,173 @@ The best resource to learn Smarty template syntax is its official documentation
[www.smarty.net](http://www.smarty.net/docs/en/). Additionally there are Yii-specific syntax extensions [www.smarty.net](http://www.smarty.net/docs/en/). Additionally there are Yii-specific syntax extensions
described below. described below.
#### Additional functions #### Setting object properties
There's a special function called `set` that allows you to set common properties of the view and controller. Currently
available properties are `title`, `theme` and `layout`:
```
{set title="My Page"}
{set theme="frontend"}
{set layout="main.tpl"}
```
For title there's dedicated block as well:
```
{title}My Page{/title}
```
#### Setting meta tags
Meta tags could be set like to following:
```
{meta keywords="Yii,PHP,Smarty,framework"}
```
There's also dedicated block for description:
```
{description}This is my page about Smarty extension{/description}
```
#### Calling object methods
Sometimes you need calling
#### Importing static classes, using widgets as functions and blocks
You can import additional static classes right in the template:
```
{use class="yii\helpers\Html"}
{Html::mailto('eugenia@example.com')}
```
If you want you can set custom alias:
```
{use class="yii\helpers\Html" as="Markup"}
{Markup::mailto('eugenia@example.com')}
```
Extension helps using widgets in convenient way converting their syntax to function calls or blocks. For regular widgets
function could be used like the following:
```
{use class='@yii\grid\GridView' type='function'}
{GridView dataProvider=$provider}
```
For widgets with `begin` and `end` methods such as ActiveForm it's better to use block:
```
{use class='yii\widgets\ActiveForm' type='block'}
{ActiveForm assign='form' id='login-form' action='/form-handler' options=['class' => 'form-horizontal']}
{$form->field($model, 'firstName')}
<div class="form-group">
<div class="col-lg-offset-1 col-lg-11">
<input type="submit" value="Login" class="btn btn-primary" />
</div>
</div>
{/ActiveForm}
```
If you're using particular widget a lot, it is a good idea to declare it in application config and remove `{use class`
call from templates:
Yii adds the following construct to the standard Smarty syntax: ```php
'components' => [
'view' => [
// ...
'renderers' => [
'tpl' => [
'class' => 'yii\smarty\ViewRenderer',
'widgets' => [
'blocks' => [
'ActiveForm' => '\yii\widgets\ActiveForm',
],
],
],
],
],
],
```
#### Referencing other templates
There are two main ways of referencing templates in `include` and `extends` statements:
```
{include 'comment.tpl'}
{extends 'post.tpl'}
{include '@app/views/snippets/avatar.tpl'}
{extends '@app/views/layouts/2columns.tpl'}
```
In the first case the view will be searched relatively to the current template path. For `comment.tpl` and `post.tpl`
that means these will be searched in the same directory as the currently rendered template.
In the second case we're using path aliases. All the Yii aliases such as `@app` are available by default.
#### CSS, JavaScript and asset bundles
In order to register JavaScript and CSS files the following syntax could be used:
```
{registerJsFile url='http://maps.google.com/maps/api/js?sensor=false' position='POS_END'}
{registerCssFile url='@assets/css/normalizer.css'}
```
If you need JavaScript and CSS directly in the template there are convenient blocks:
```
{registerJs key='show' position='POS_LOAD'}
$("span.show").replaceWith('<div class="show">');
{/registerJs}
{registerCss}
div.header {
background-color: #3366bd;
color: white;
}
{/registerCss}
```
Asset bundles could be registered the following way:
```
{use class="yii\web\JqueryAsset"}
{JqueryAsset::register($this)|void}
```
Here we're using `void` modifier because we don't need method call result.
#### URLs
There are two functions you can use for building URLs:
```php ```php
<a href="{path route='blog/view' alias=$post.alias}">{$post.title}</a> <a href="{path route='blog/view' alias=$post.alias}">{$post.title}</a>
<a href="{url route='blog/view' alias=$post.alias}">{$post.title}</a>
``` ```
Internally, the `path()` function calls Yii's `Url::to()` method. `path` generates relative URL while `url` generates absolute one. Internally both are using [[\yii\helpers\Url]].
#### Additional variables #### Additional variables
Within Smarty templates, you can also make use of these variables: Within Smarty templates the following variables are always defined:
- `$app`, which equates to `\Yii::$app` - `$app`, which equates to `\Yii::$app`
- `$this`, which equates to the current `View` object - `$this`, which equates to the current `View` object
#### Accessing config params
Yii parameters that are available in your application through `Yii::$app->params->something` could be used the following
way:
```
`{#something#}`
```
...@@ -4,8 +4,26 @@ Yii Framework 2 smarty extension Change Log ...@@ -4,8 +4,26 @@ Yii Framework 2 smarty extension Change Log
2.0.0-rc under development 2.0.0-rc under development
-------------------------- --------------------------
- no changes in this release. - Enh #4619 (samdark, hwmaier)
- New functions:
- `url` generates absolute URL.
- `set` allows setting commonly used view paramters: `title`, `theme` and `layout`.
- `meta` registers meta tag.
- `registerJsFile` registers JavaScript file.
- `registerCssFile` registers CSS file.
- `use` allows importing classes to the template and optionally provides these as functions and blocks.
- New blocks:
- `title`.
- `description`.
- `registerJs`.
- `registerCss`.
- New modifier `void` that allows calling functions and ignoring result.
- Moved most of Yii custom syntax into `\yii\smarty\Extension` class that could be extended via `extensionClass` property.
- Added ability to set Smarty options via config using `options`.
- Added `imports` property that accepts an array of classes imported into template namespace.
- Added `widgets` property that can be used to import widgets as Smarty tags.
- `Yii::$app->params['paramKey']` values are now accessible as Smarty config variables `{#paramKey#}`.
- Added ability to use Yii aliases in `extends` and `require`.
2.0.0-beta April 13, 2014 2.0.0-beta April 13, 2014
------------------------- -------------------------
......
...@@ -10,6 +10,7 @@ namespace yiiunit\extensions\smarty; ...@@ -10,6 +10,7 @@ namespace yiiunit\extensions\smarty;
use yii\web\AssetManager; use yii\web\AssetManager;
use yii\web\View; use yii\web\View;
use Yii; use Yii;
use yiiunit\data\base\Singer;
use yiiunit\TestCase; use yiiunit\TestCase;
/** /**
...@@ -41,6 +42,47 @@ class ViewRendererTest extends TestCase ...@@ -41,6 +42,47 @@ class ViewRendererTest extends TestCase
$this->assertEquals('test view Hello World!.', $content); $this->assertEquals('test view Hello World!.', $content);
} }
public function testLayoutAssets()
{
$view = $this->mockView();
$content = $view->renderFile('@yiiunit/extensions/smarty/views/layout.tpl');
$this->assertEquals(1, preg_match('#<script src="/assets/[0-9a-z]+/jquery\\.js"></script>\s*</body>#', $content), 'Content does not contain the jquery js:' . $content);
}
public function testChangeTitle()
{
$view = $this->mockView();
$view->title = 'Original title';
$content = $view->renderFile('@yiiunit/extensions/smarty/views/changeTitle.tpl');
$this->assertTrue(strpos($content, 'New title') !== false, 'New title should be there:' . $content);
$this->assertFalse(strpos($content, 'Original title') !== false, 'Original title should not be there:' . $content);
}
public function testForm()
{
$view = $this->mockView();
$model = new Singer();
$content = $view->renderFile('@yiiunit/extensions/smarty/views/form.tpl', ['model' => $model]);
$this->assertEquals(1, preg_match('#<form id="login-form" class="form-horizontal" action="/form-handler" method="post">.*?</form>#s', $content), 'Content does not contain form:' . $content);
}
public function testInheritance()
{
$view = $this->mockView();
$content = $view->renderFile('@yiiunit/extensions/smarty/views/extends2.tpl');
$this->assertTrue(strpos($content, 'Hello, I\'m inheritance test!') !== false, 'Hello, I\'m inheritance test! should be there:' . $content);
$this->assertTrue(strpos($content, 'extends2 block') !== false, 'extends2 block should be there:' . $content);
$this->assertFalse(strpos($content, 'extends1 block') !== false, 'extends1 block should not be there:' . $content);
$content = $view->renderFile('@yiiunit/extensions/smarty/views/extends3.tpl');
$this->assertTrue(strpos($content, 'Hello, I\'m inheritance test!') !== false, 'Hello, I\'m inheritance test! should be there:' . $content);
$this->assertTrue(strpos($content, 'extends3 block') !== false, 'extends3 block should be there:' . $content);
$this->assertFalse(strpos($content, 'extends1 block') !== false, 'extends1 block should not be there:' . $content);
}
/** /**
* @return View * @return View
*/ */
...@@ -50,6 +92,9 @@ class ViewRendererTest extends TestCase ...@@ -50,6 +92,9 @@ class ViewRendererTest extends TestCase
'renderers' => [ 'renderers' => [
'tpl' => [ 'tpl' => [
'class' => 'yii\smarty\ViewRenderer', 'class' => 'yii\smarty\ViewRenderer',
'options' => [
'force_compile' => true, // always recompile templates, don't do it in production
],
], ],
], ],
'assetManager' => $this->mockAssetManager(), 'assetManager' => $this->mockAssetManager(),
......
{set title='New title'}
<title>{$this->title}</title>
\ No newline at end of file
Hello, I'm inheritance test!
{block name=test}
extends1 block
{/block}
\ No newline at end of file
{extends file="@yiiunit/extensions/smarty/views/extends1.tpl"}
{block name=test}
extends2 block
{/block}
\ No newline at end of file
{extends file="@yiiunit/extensions/smarty/views/extends1.tpl"}
{block name=test}
extends3 block
{/block}
\ No newline at end of file
{use class='yii\widgets\ActiveForm' type='block'}
{ActiveForm assign='form' id='login-form' action='/form-handler' options=['class' => 'form-horizontal']}
{$form->field($model, 'firstName')}
<div class="form-group">
<div class="col-lg-offset-1 col-lg-11">
<input type="submit" value="Login" class="btn btn-primary" />
</div>
</div>
{/ActiveForm}
\ No newline at end of file
{use class="yii\web\JqueryAsset"}
{JqueryAsset::register($this)|void}
{$this->beginPage()}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="{$app->charset}"/>
<title>{$this->title|escape}</title>
{$this->head()}
</head>
<body>
{$this->beginBody()}
body
{$this->endBody()}
</body>
{$this->endPage()}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment