视图助手(View Helpers)

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

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

本指南不是一个完整的视图助手使用文档,完整说明请查看 Phalcon\Tag

文档类型(Document Type of Content)

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.

Available document type constants in Phalcon\Tag namespace are:

Constant Document type
HTML32 HTML 3.2
HTML401_STRICT HTML 4.01 Strict
HTML401_TRANSITIONAL HTML 4.01 Transitional
HTML401_FRAMESET HTML 4.01 Frameset
HTML5 HTML 5
XHTML10_STRICT XHTML 1.0 Strict
XHTML10_TRANSITIONAL XHTML 1.0 Transitional
XHTML10_FRAMESET XHTML 1.0 Frameset
XHTML11 XHTML 1.1
XHTML20 XHTML 2.0
XHTML5 XHTML 5

Setting document type.

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

Getting document type.

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

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.  
  4. <!-- with CSS attributes -->
  5. <?= $this->tag->linkTo(array('products/edit/10', 'Edit', 'class' => 'edit-btn')) ?>
  6.  
  7. <!-- for a named route -->
  8. <?= $this->tag->linkTo(array(array('for' => 'show-product', 'title' => 123, 'name' => 'carrots'), 'Show')) ?>

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

创建表单(Creating Forms)

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.  
  8. <!-- Specifying another method or attributes for the FORM tag -->
  9. <?= $this->tag->form(array("products/search", "method" => "get")); ?>
  10. <label for="q">Search:</label>
  11. <?= $this->tag->textField("q"); ?>
  12. <?= $this->tag->submitButton("Search"); ?>
  13. <?= $this->tag->endForm() ?>

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>

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

使用助手生成表单控件(Helpers to Generate Form Elements)

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

使用选择框(Making Select Boxes)

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.  
  3. // Using data from a resultset
  4. echo $this->tag->select(
  5. array(
  6. "productId",
  7. Products::find("type = 'vegetables'"),
  8. "using" => array("id", "name")
  9. )
  10. );
  11.  
  12. // Using data from an array
  13. echo $this->tag->selectStatic(
  14. array(
  15. "status",
  16. array(
  17. "A" => "Active",
  18. "I" => "Inactive",
  19. )
  20. )
  21. );
  22.  
  23. echo $this->tag->select(array(
  24. 'robotid',
  25. Rbots::find(),
  26. 'using' => ['id', function($robot) {
  27. return $item->name.'('.$$robot->id.')';
  28. }],
  29. 'value' => $this->requset('robotid'),
  30. 'useEmpey' => true,
  31. 'class' => 'form-control',
  32. ));

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.  
  7. <select id="status" name="status">
  8. <option value="A">Active</option>
  9. <option value="I">Inactive</option>
  10. </select>

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

  1. <?php
  2.  
  3. // Creating a Select Tag with an empty option
  4. echo $this->tag->select(
  5. array(
  6. "productId",
  7. Products::find("type = 'vegetables'"),
  8. "using" => array("id", "name"),
  9. "useEmpty" => true
  10. )
  11. );

Produces this HTML:

  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.  
  3. // Creating a Select Tag with an empty option with default text
  4. echo $this->tag->select(
  5. array(
  6. 'productId',
  7. Products::find("type = 'vegetables'"),
  8. 'using' => array('id', "name"),
  9. 'useEmpty' => true,
  10. 'emptyText' => 'Please, choose one...',
  11. 'emptyValue' => '@'
  12. )
  13. );
  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>

设置 HTML 属性(Assigning HTML attributes)

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. ) ?>

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)

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 hasa 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.  
  3. use Phalcon\Mvc\Controller;
  4.  
  5. class ProductsController extends Controller
  6. {
  7. public function indexAction()
  8. {
  9. $this->tag->setDefault("color", "Blue");
  10. }
  11. }

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

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

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)

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

直接设置值(Specifying values directly)

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.

所有的表单方法都支持参数 value。你可以直接设置一个明确的值给表单方法。当这个值被明确设定的时候,任何通过 setDefault() 或者通过 请求(request) 所设置的值将被直接忽略。

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

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

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

The following HTML will generated:

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

设置标题分隔符(Set The Title Separator)

设置标题分隔符,用以连接追加或前置的标题内容:

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

将生成如下的 HTML 内容:

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

静态内容助手(Static Content Helpers)

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.  
  3. // Generate <img src="/your-app/img/hello.gif">
  4. echo $this->tag->image("img/hello.gif");
  5.  
  6. // Generate <img alt="alternative text" src="/your-app/img/hello.gif">
  7. echo $this->tag->image(
  8. array(
  9. "img/hello.gif",
  10. "alt" => "alternative text"
  11. )
  12. );

样式表(Stylesheets)

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

脚本(Javascript)

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

HTML5 对象(HTML5 elements - generic HTML helper)

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

标签服务(Tag Service)

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

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

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

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

Then change the definition of the service ‘tag’:

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

创建助手(Creating your own helpers)

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

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

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

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

原文: http://www.myleftstudio.com/reference/tags.html