视图助手View Helpers

编写和维护HTML标记很快就会变成一个乏味的任务,因为命名约定和众多的属性需要被考虑。Phalcon提供:doc:`Phalcon\Tag <../api/Phalcon_Tag>`来处理这些复杂的工作,使用视图助手来生成HTML标记。

Writing and maintaining HTML markup can quickly become a tedious task because of the naming conventions and numerous attributes that have to be taken into consideration. Phalcon deals with this complexity by offering Phalcon\Tag, which in turn offers view helpers to generate HTML markup.

该组件可被用在一个纯HTML + PHP视图或:doc:`Volt <volt>`模板。

This component can be used in a plain HTML+PHP view or in a Volt template.

本指南并不打算成为一个完整的文档,更多的使用说明请参考:doc:`Phalcon\Tag <../api/Phalcon_Tag>`页面的完整的api说明。

This guide is not intended to be a complete documentation of available helpers and their arguments. Please visit the Phalcon\Tag page in the API for a complete reference.

文档内容的类型Document Type of Content

Phalcon提供Phalcon\Tag::setDoctype() 辅助设置文档内容的类型。文档类型设置可能会影响到其他标签产生的HTML输出。例如,如果设置XHTML文档类型,返回或输出HTML标签会产生遵循标准的XHTML闭合标记。

Phalcon provides Phalcon\Tag::setDoctype() helper to set document type of the content. Document type setting may affect HTML output produced by other tag helpers. For example, if you set XHTML document type family, helpers that return or output HTML tags will produce self-closing tags to follow valid XHTML standard.

Phalcon\Tag命名空间可用的文档类型:

Available document type constants in Phalcon\Tag namespace are:

ConstantDocument type
HTML32HTML 3.2
HTML401_STRICTHTML 4.01 Strict
HTML401_TRANSITIONALHTML 4.01 Transitional
HTML401_FRAMESETHTML 4.01 Frameset
HTML5HTML 5
XHTML10_STRICTXHTML 1.0 Strict
XHTML10_TRANSITIONALXHTML 1.0 Transitional
XHTML10_FRAMESETXHTML 1.0 Frameset
XHTML11XHTML 1.1
XHTML20XHTML 2.0
XHTML5XHTML 5

设置文档类型

Setting document type.

  1. <?php
  2. use Phalcon\Tag;
  3. $this->tag->setDoctype(Tag::HTML401_STRICT);
  4. ?>

获得文档类型

Getting document type.

  1. <?= $this->tag->getDoctype() ?>
  2. <html>
  3. <!-- your HTML code -->
  4. </html>

会产生如下HTML代码

The following HTML will be produced.

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
  2. "http://www.w3.org/TR/html4/strict.dtd">
  3. <html>
  4. <!-- your HTML code -->
  5. </html>

Volt语法:

Volt syntax:

  1. {{ get_doctype() }}
  2. <html>
  3. <!-- your HTML code -->
  4. </html>

生成链接Generating Links

一个真正的任何web应用程序或网站的共同任务是产生链接,让我们从一个页面导航到另一个地方。我们可以用以下方法创建内部url:

A real common task in any web application or website is to produce links that allow us to navigate from one page to another. When they are internal URLs we can create them in the following manner:

  1. <!-- for the default route -->
  2. <?= $this->tag->linkTo("products/search", "Search") ?>
  3. <!-- with CSS attributes -->
  4. <?= $this->tag->linkTo(array('products/edit/10', 'Edit', 'class' => 'edit-btn')) ?>
  5. <!-- for a named route -->
  6. <?= $this->tag->linkTo(array(array('for' => 'show-product', 'title' => 123, 'name' => 'carrots'), 'Show')) ?>

所有链接通过 :doc:`Phalcon\Mvc\Url <url>`组件来产生

Actually, all produced URLs are generated by the component Phalcon\Mvc\Url (or service “url” failing)

一些链接通过Volt来生成:

Same links generated with Volt:

  1. <!-- for the default route -->
  2. {{ link_to("products/search", "Search") }}
  3. <!-- for a named route -->
  4. {{ link_to(['for': 'show-product', 'id': 123, 'name': 'carrots'], 'Show') }}
  5. <!-- for a named route with class -->
  6. {{ link_to(['for': 'show-product', 'id': 123, 'name': 'carrots'], 'Show','class'=>'edit-btn') }}

创建表单Creating Forms

表单在web应用程序中获取用户输入,是一个非常重要组成部分。下面的例子展示了如何通过使用视图助手实现一个简单的搜索表单:

Forms in web applications play an essential part in retrieving user input. The following example shows how to implement a simple search form using view helpers:

  1. <!-- Sending the form by method POST -->
  2. <?= $this->tag->form("products/search") ?>
  3. <label for="q">Search:</label>
  4. <?= $this->tag->textField("q") ?>
  5. <?= $this->tag->submitButton("Search") ?>
  6. <?= $this->tag->endForm() ?>
  7. <!-- Specifying another method or attributes for the FORM tag -->
  8. <?= $this->tag->form(array("products/search", "method" => "get")); ?>
  9. <label for="q">Search:</label>
  10. <?= $this->tag->textField("q"); ?>
  11. <?= $this->tag->submitButton("Search"); ?>
  12. <?= $this->tag->endForm() ?>

这最后的代码将生成以下HTML:

This last code will generate the following HTML:

  1. <form action="/store/products/search/" method="get">
  2. <label for="q">Search:</label>
  3. <input type="text" id="q" value="" name="q" />
  4. <input type="submit" value="Search" />
  5. </form>

在Volt中生成同样的表单:

Same form generated in Volt:

  1. <!-- Specifying another method or attributes for the FORM tag -->
  2. {{ form("products/search", "method": "get") }}
  3. <label for="q">Search:</label>
  4. {{ text_field("q") }}
  5. {{ submit_button("Search") }}
  6. {{ endform() }}

Phalcon为面向对象创建表单提供:doc:`form builder <forms>`组件。

Phalcon also provides a form builder to create forms in an object-oriented manner.

生成表单元素的视图助手Helpers to Generate Form Elements

Phalcon提供了一系列的用于生成表单元素的助手,例如:文本框,按钮等。视图助手的第一个参数是生成元素的名称。提交表单时,将通过表单传递同名数据。在一个控制器可以在请求对象上($this->request)通过使用getPost()和getQuery()方法得到相同的名称的数值。

Phalcon provides a series of helpers to generate form elements such as text fields, buttons and more. The first parameter of each helper is always the name of the element to be generated. When the form is submitted, the name will be passed along with the form data. In a controller you can get these values using the same name by using the getPost() and getQuery() methods on the request object ($this->request).

  1. <?php echo $this->tag->textField("username") ?>
  2. <?php echo $this->tag->textArea(array(
  3. "comment",
  4. "This is the content of the text-area",
  5. "cols" => "6",
  6. "rows" => 20
  7. )) ?>
  8. <?php echo $this->tag->passwordField(array(
  9. "password",
  10. "size" => 30
  11. )) ?>
  12. <?php echo $this->tag->hiddenField(array(
  13. "parent_id",
  14. "value"=> "5"
  15. )) ?>

Volt语法:

Volt syntax:

  1. {{ text_field("username") }}
  2. {{ text_area("comment", "This is the content", "cols": "6", "rows": 20) }}
  3. {{ password_field("password", "size": 30) }}
  4. {{ hidden_field("parent_id", "value": "5") }}

做筛选框Making Select Boxes

生成选择框是很容易的,尤其是如果相关数据存储在PHP关联数组。选择元素的视图助手为Phalcon\Tag::select() 和Phalcon\Tag::selectStatic()。Phalcon\Tag::select()是专门设计用于处理:doc:`Phalcon\Mvc\Model <models>`数据的,Phalcon\Tag::selectStatic()可以使用PHP数组。

Generating select boxes (select box) is easy, especially if the related data is stored in PHP associative arrays. The helpers for select elements are Phalcon\Tag::select() and Phalcon\Tag::selectStatic(). Phalcon\Tag::select() has been was specifically designed to work with Phalcon\Mvc\Model, while Phalcon\Tag::selectStatic() can with PHP arrays.

  1. <?php
  2. // Using data from a resultset
  3. echo $this->tag->select(
  4. array(
  5. "productId",
  6. Products::find("type = 'vegetables'"),
  7. "using" => array("id", "name")
  8. )
  9. );
  10. // Using data from an array
  11. echo $this->tag->selectStatic(
  12. array(
  13. "status",
  14. array(
  15. "A" => "Active",
  16. "I" => "Inactive",
  17. )
  18. )
  19. );

将会产生如下HTML代码:

The following HTML will generated:

  1. <select id="productId" name="productId">
  2. <option value="101">Tomato</option>
  3. <option value="102">Lettuce</option>
  4. <option value="103">Beans</option>
  5. </select>
  6. <select id="status" name="status">
  7. <option value="A">Active</option>
  8. <option value="I">Inactive</option>
  9. </select>

可以添加一个空白的option到产生的html中:

You can add an “empty” option to the generated HTML:

  1. <?php
  2. // Creating a Select Tag with an empty option
  3. echo $this->tag->select(
  4. array(
  5. "productId",
  6. Products::find("type = 'vegetables'"),
  7. "using" => array("id", "name"),
  8. "useEmpty" => true
  9. )
  10. );
  1. <select id="productId" name="productId">
  2. <option value="">Choose..</option>
  3. <option value="101">Tomato</option>
  4. <option value="102">Lettuce</option>
  5. <option value="103">Beans</option>
  6. </select>
  1. <?php
  2. // Creating a Select Tag with an empty option with default text
  3. echo $this->tag->select(
  4. array(
  5. 'productId',
  6. Products::find("type = 'vegetables'"),
  7. 'using' => array('id', "name"),
  8. 'useEmpty' => true,
  9. 'emptyText' => 'Please, choose one...',
  10. 'emptyValue' => '@'
  11. )
  12. );
  1. <select id="productId" name="productId">
  2. <option value="@">Please, choose one..</option>
  3. <option value="101">Tomato</option>
  4. <option value="102">Lettuce</option>
  5. <option value="103">Beans</option>
  6. </select>

用Volt实现如上的代码:

Volt syntax for above example:

  1. {# Creating a Select Tag with an empty option with default text #}
  2. {{ select('productId', products, 'using': ['id', 'name'],
  3. 'useEmpty': true, 'emptyText': 'Please, choose one...', 'emptyValue': '@') }}

HTML属性赋值Assigning HTML attributes

所有的视图助手接受数组作为其第一个参数,可以包含额外的HTML属性用于元素的生成。

All the helpers accept an array as their first parameter which can contain additional HTML attributes for the element generated.

  1. <?php $this->tag->textField(
  2. array(
  3. "price",
  4. "size" => 20,
  5. "maxlength" => 30,
  6. "placeholder" => "Enter a price",
  7. )
  8. ) ?>

使用Volt如下:

or using Volt:

  1. {{ text_field("price", "size": 20, "maxlength": 30, "placeholder": "Enter a price") }}

产生的html如下:

The following HTML is generated:

  1. <input type="text" name="price" id="price" size="20" maxlength="30"
  2. placeholder="Enter a price" />

设置视图助手值Setting Helper Values

控制器中视图助手From Controllers

在MVC框架为表单元素在视图中设置特定的默认值是一个好的编程原则。可以直接从控制器使用Phalcon\Tag::setDefault()设置这些值。这个助手预先设置了所有在视图中其他助手的默认值。如果任何助手中名称匹配预加载的默认值,则将使用这个默认值,除非是在视图中直接指定一个默认值。

It is a good programming principle for MVC frameworks to set specific values for form elements in the view. You can set those values directly from the controller using Phalcon\Tag::setDefault(). This helper preloads a value for any helpers present in the view. If any helper in the view has a name that matches the preloaded value, it will use it, unless a value is directly assigned on the helper in the view.

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class ProductsController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. $this->tag->setDefault("color", "Blue");
  8. }
  9. }

在视图中,selectStatic助手匹配的值将会使用默认值,在这个例子中就是color

At the view, a selectStatic helper matches the same index used to preset the value. In this case “color”:

  1. <?php
  2. echo $this->tag->selectStatic(
  3. array(
  4. "color",
  5. array(
  6. "Yellow" => "Yellow",
  7. "Blue" => "Blue",
  8. "Red" => "Red"
  9. )
  10. )
  11. );

将会产生如下”Blue”为选中状态的默认值:

This will generate the following select tag with the value “Blue” selected:

  1. <select id="color" name="color">
  2. <option value="Yellow">Yellow</option>
  3. <option value="Blue" selected="selected">Blue</option>
  4. <option value="Red">Red</option>
  5. </select>

请求中的视图助手From the Request

:doc:`Phalcon\Tag <../api/Phalcon_Tag>`提供一个特殊功能,在请求的时候视图助手提供了简便的验证提示信息并且不会丢失已经输入的信息。

A special feature that the Phalcon\Tag helpers have is that they keep the values of form helpers between requests. This way you can easily show validation messages without losing entered data.

直接设置值Specifying values directly

视图助手都有”value”属性。可以直接设置视图助手的值。如果直接设置了值,则将忽略setDefault()设置的值以及请求过来的值。

Every form helper supports the parameter “value”. With it you can specify a value for the helper directly. When this parameter is present, any preset value using setDefault() or via request will be ignored.

动态设置文档标题Changing dynamically the Document Title

:doc:`Phalcon\Tag <../api/Phalcon_Tag>`提供了在控制器中动态改变文档标题的功能。

Phalcon\Tag offers helpers to change dynamically the document title from the controller. The following example demonstrates just that:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class PostsController extends Controller
  4. {
  5. public function initialize()
  6. {
  7. $this->tag->setTitle("Your Website");
  8. }
  9. public function indexAction()
  10. {
  11. $this->tag->prependTitle("Index of Posts - ");
  12. }
  13. }
  1. <html>
  2. <head>
  3. <?php echo $this->tag->getTitle(); ?>
  4. </head>
  5. <body>
  6. </body>
  7. </html>

将会产生如下代码:

The following HTML will generated:

  1. <html>
  2. <head>
  3. <title>Index of Posts - Your Website</title>
  4. </head>
  5. <body>
  6. </body>
  7. </html>

静态内容助手Static Content Helpers

:doc:`Phalcon\Tag <../api/Phalcon_Tag>`提供了产生script, link 或者 img的标签。帮助我们快速产生代码。

Phalcon\Tag also provide helpers to generate tags such as script, link or img. They aid in quick and easy generation of the static resources of your application

图片Images

  1. <?php
  2. // Generate <img src="/your-app/img/hello.gif">
  3. echo $this->tag->image("img/hello.gif");
  4. // Generate <img alt="alternative text" src="/your-app/img/hello.gif">
  5. echo $this->tag->image(
  6. array(
  7. "img/hello.gif",
  8. "alt" => "alternative text"
  9. )
  10. );

Volt 语法:

Volt syntax:

  1. {# Generate <img src="/your-app/img/hello.gif"> #}
  2. {{ image("img/hello.gif") }}
  3. {# Generate <img alt="alternative text" src="/your-app/img/hello.gif"> #}
  4. {{ image("img/hello.gif", "alt": "alternative text") }}

css样式Stylesheets

  1. <?php
  2. // Generate <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Rosario" type="text/css">
  3. echo $this->tag->stylesheetLink("http://fonts.googleapis.com/css?family=Rosario", false);
  4. // Generate <link rel="stylesheet" href="/your-app/css/styles.css" type="text/css">
  5. echo $this->tag->stylesheetLink("css/styles.css");

Volt 语法:

Volt syntax:

  1. {# Generate <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Rosario" type="text/css"> #}
  2. {{ stylesheet_link("http://fonts.googleapis.com/css?family=Rosario", false) }}
  3. {# Generate <link rel="stylesheet" href="/your-app/css/styles.css" type="text/css"> #}
  4. {{ stylesheet_link("css/styles.css") }}

Javascript

  1. <?php
  2. // Generate <script src="http://localhost/javascript/jquery.min.js" type="text/javascript"></script>
  3. echo $this->tag->javascriptInclude("http://localhost/javascript/jquery.min.js", false);
  4. // Generate <script src="/your-app/javascript/jquery.min.js" type="text/javascript"></script>
  5. echo $this->tag->javascriptInclude("javascript/jquery.min.js");

Volt 语法:

Volt syntax:

  1. {# Generate <script src="http://localhost/javascript/jquery.min.js" type="text/javascript"></script> #}
  2. {{ javascript_include("http://localhost/javascript/jquery.min.js", false) }}
  3. {# Generate <script src="/your-app/javascript/jquery.min.js" type="text/javascript"></script> #}
  4. {{ javascript_include("javascript/jquery.min.js") }}

HTML5 对象 HTML5 elements - generic HTML helper

Phalcon 提供了生成任何HTML元素的标签助手。由开发人员为视图助手生成一个有效的HTML元素名。

Phalcon offers a generic HTML helper that allows the generation of any kind of HTML element. It is up to the developer to produce a valid HTML element name to the helper.

  1. <?php
  2. // Generate
  3. // <canvas id="canvas1" width="300" class="cnvclass">
  4. // This is my canvas
  5. // </canvas>
  6. echo $this->tag->tagHtml("canvas", array("id" => "canvas1", "width" => "300", "class" => "cnvclass"), false, true, true);
  7. echo "This is my canvas";
  8. echo $this->tag->tagHtmlClose("canvas");

Volt 语法:

Volt syntax:

  1. {# Generate
  2. <canvas id="canvas1" width="300" class="cnvclass">
  3. This is my canvas
  4. </canvas> #}
  5. {{ tag_html("canvas", ["id": "canvas1", width": "300", "class": "cnvclass"], false, true, true) }}
  6. This is my canvas
  7. {{ tag_html_close("canvas") }}

标签服务Tag Service

:doc:`Phalcon\Tag <../api/Phalcon_Tag>`通过使用’tag‘服务来生效。这就意味着在应用中任何包含服务应用的地方可以使用它。

Phalcon\Tag is available via the ‘tag’ service, this means you can access it from any part of the application where the services container is located:

  1. <?php echo $this->tag->linkTo('pages/about', 'About') ?>

可以方便的定义一个新的视图助手去替换服务容器中的’tag‘服务:

You can easily add new helpers to a custom component replacing the service ‘tag’ in the services container:

  1. <?php
  2. use Phalcon\Tag;
  3. class MyTags extends Tag
  4. {
  5. //...
  6. //Create a new helper
  7. static public function myAmazingHelper($parameters)
  8. {
  9. //...
  10. }
  11. //Override an existing method
  12. static public function textField($parameters)
  13. {
  14. //...
  15. }
  16. }

然后替换’tag‘服务定义:

Then change the definition of the service ‘tag’:

  1. <?php
  2. $di['tag'] = function() {
  3. return new MyTags();
  4. };

创建助手Creating your own helpers

可以方便的创建助手,第一步,在controller和models的同级目录创建一个以视图助手名称命名的文件,在文件中创建一个``MyTags.php``文件。如``/app/customhelpers/MyTags.php``目录结构。在``MyTags.php``文件中我们扩展 Phalcon\Tag 并实现自己的代码。下面就是自定义助手的例子:

You can easily create your own helpers. First, start by creating a new folder within the same directory as your controllers and models. Give it a title that is relative to what you are creating. For our example here, we can call it “customhelpers”. Next we will create a new file titled MyTags.php within this new directory. At this point, we have a structure that looks similar to : /app/customhelpers/MyTags.php. In MyTags.php, we will extend the Phalcon\Tag and implement your own helper. Below is a simple example of a custom helper:

  1. <?php
  2. use Phalcon\Tag;
  3. class MyTags extends Tag
  4. {
  5. /**
  6. * Generates a widget to show a HTML5 audio tag
  7. *
  8. * @param array
  9. * @return string
  10. */
  11. static public function audioField($parameters)
  12. {
  13. // Converting parameters to array if it is not
  14. if (!is_array($parameters)) {
  15. $parameters = array($parameters);
  16. }
  17. // Determining attributes "id" and "name"
  18. if (!isset($parameters[0])) {
  19. $parameters[0] = $parameters["id"];
  20. }
  21. $id = $parameters[0];
  22. if (!isset($parameters["name"])) {
  23. $parameters["name"] = $id;
  24. } else {
  25. if (!$parameters["name"]) {
  26. $parameters["name"] = $id;
  27. }
  28. }
  29. // Determining widget value,
  30. // \Phalcon\Tag::setDefault() allows to set the widget value
  31. if (isset($parameters["value"])) {
  32. $value = $parameters["value"];
  33. unset($parameters["value"]);
  34. } else {
  35. $value = self::getValue($id);
  36. }
  37. // Generate the tag code
  38. $code = '<audio id="'.$id.'" value="'.$value.'" ';
  39. foreach ($parameters as $key => $attributeValue) {
  40. if (!is_integer($key)) {
  41. $code.= $key.'="'.$attributeValue.'" ';
  42. }
  43. }
  44. $code.=" />";
  45. return $code;
  46. }
  47. }

创建完自定义助手后,我们需要在index.php中自动加载上我们的助手目录。

After creating our custom helper, we will autoload the new directory that contains our helper class from our “index.php” located in the public directory.

  1. <?php
  2. use Phalcon\Loader;
  3. use Phalcon\Mvc\Application;
  4. use Phalcon\DI\FactoryDefault();
  5. use Phalcon\Exception as PhalconException;
  6. try {
  7. $loader = new Loader();
  8. $loader->registerDirs(array(
  9. '../app/controllers',
  10. '../app/models',
  11. '../app/customhelpers' // Add the new helpers folder
  12. ))->register();
  13. $di = new FactoryDefault();
  14. // Assign our new tag a definition so we can call it
  15. $di->set('MyTags', function()
  16. {
  17. return new MyTags();
  18. });
  19. $application = new Application($di);
  20. echo $application->handle()->getContent();
  21. } catch(PhalconException $e) {
  22. echo "PhalconException: ", $e->getMessage();
  23. }
  24. }

现在我们就可以视图中使用我们的新视图助手了:

Now you are ready to use your new helper within your views:

  1. <body>
  2. <?php
  3. echo MyTags::audioField(array(
  4. 'name' => 'test',
  5. 'id' => 'audio_test',
  6. 'src' => '/path/to/audio.mp3'
  7. ));
  8. ?>
  9. </body>

下面我们将介绍一个非常快的PHP模板引擎 Volt ,在里面我们使用和Phalcon\Tag相同的语法。

In next chapter, we’ll talk about Volt a faster template engine for PHP, where you can use a more friendly syntax for using helpers provided by Phalcon\Tag.