程序员人生 网站导航

Symfony (III): View

栏目:access时间:2014-10-18 08:00:00


Templating

Listing 7-1 shows a typical symfony template. It contains some HTML code and some basic PHP code, usually calls to variables defined in the action (via $this->name = 'foo';) and helpers.

Listing 7-1 - A Sample indexSuccess.php Template

<h1>Welcome</h1>
<p>Welcome back, <?php echo $name ?>!</p>
<ul>What would you like to do?
  <li><?php echo link_to('Read the last articles', 'article/read') ?></li>
  <li><?php echo link_to('Start writing a new one', 'article/write') ?></li>
</ul>
 

Helpers

 

<?php echo input_tag('nickname') ?>
 => <input type="text" name="nickname" id="nickname" value="" />
 

Sample Helper Definition

function input_tag($name, $value = null)
{
  return '<input type="text" name="'.$name.'" id="'.$name.'"value="'.$value.'" />';
}
 

Declaring Helpers

Declaring the Use of a Helper

// Use a specific helper group in this template
<?php use_helper('Text') ?>
...
<h1>Description</h1>
<p><?php echo auto_link_text($description) ?></p>
 
If you need to declare more than one helper group, add more arguments to the use_helper() call. For instance, to load both the Text and the Javascript helper groups in a template, call <?php echo use_helper('Text', 'Javascript') ?>`.
 

A few helpers are available by default in every template, without need for declaration. These are helpers of the following helper groups:

  • Helper: Required for helper inclusion (the use_helper() function is, in fact, a helper itself)
  • Tag: Basic tag helper, used by almost every helper
  • Url: Links and URL management helpers
  • Asset: Helpers populating the HTML <head> section, and providing easy links to external assets (images, JavaScript, and style sheet files)
  • Partial: Helpers allowing for inclusion of template fragments
  • Cache: Manipulation of cached code fragments
  • Form: Form input helpers

The list of the standard helpers, loaded by default for every template, is configurable in the settings.yml file.

Frequently Used Helpers

You will learn about some helpers in detail in later chapters, in relation with the feature they are helping. Listing 7-4 gives a brief list of the default helpers that are used a lot, together with the HTML code they return.

Listing 7-4 - Common Default Helpers

// Helper group
<?php use_helper('HelperName') ?>
<?php use_helper('HelperName1', 'HelperName2', 'HelperName3') ?>
 
// Tag group
<?php echo tag('input', array('name' => 'foo', 'type' => 'text')) ?>
<?php echo tag('input', 'name=foo type=text') ?>  // Alternative options syntax
 => <input name="foo" type="text" />
<?php echo content_tag('textarea', 'dummy content', 'name=foo') ?>
 => <textarea name="foo">dummy content</textarea>
 
// Url group
<?php echo link_to('click me', 'mymodule/myaction') ?>
=> <a href="/route/to/myaction">click me</a>  // Depends on the routing settings
 
// Asset group
<?php echo image_tag('myimage', 'alt=foo size=200x100') ?>
 => <img src="/images/myimage.png" alt="foo" width="200" height="100"/>
<?php echo javascript_include_tag('myscript') ?>
 => <script language="JavaScript" type="text/javascript" src="/js/myscript.js"></script>
<?php echo stylesheet_tag('style') ?>
 => <link href="/stylesheets/style.css" media="screen" rel="stylesheet"type="text/css" />
 

Page Layout

The template shown in Listing 7-1 is not a valid XHTML document. The DOCTYPE definition and the <html> and <body> tags are missing. That's because they are stored somewhere else in the application, in a file called layout.php, which contains the page layout. This file, also called the global template, stores the HTML code that is common to all pages of the application to avoid repeating it in every template. The content of the template is integrated into the layout, or, if you change the point of view, the layout "decorates" the template. This is an application of the decorator design pattern, illustrated in Figure 7-1.

For more information about the decorator and other design patterns, see Patterns of Enterprise Application Architecture by Martin Fowler (Addison-Wesley, ISBN: 0-32112-742-0).

Figure 7-1 - Decorating a template with a layout

Decorating a template with a layout

Listing 7-5 - Default Layout, in myproject/apps/myapp/templates/layout.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <?php echo include_http_metas() ?>
  <?php echo include_metas() ?>
  <?php echo include_title() ?>
  <link rel="shortcut icon" href="/favicon.ico" />
</head>
<body>
 
<?php echo $sf_data->getRaw('sf_content') ?>
 
</body>
</html>
 

The helpers called in the <head> section grab information from the response object and the view configuration. The <body> tag outputs the result of the template. With this layout, the default configuration, and the sample template in Listing 7-1, the processed view looks like Listing 7-6.

Listing 7-6 - The Layout, the View Configuration, and the Template Assembled

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <meta name="title" content="symfony project" />
  <meta name="robots" content="index, follow" />
  <meta name="description" content="symfony project" />
  <meta name="keywords" content="symfony, project" />
  <title>symfony project</title>
  <link rel="stylesheet" type="text/css" href="/css/main.css" />
  <link rel="shortcut icon" href="/favicon.ico">
</head>
<body>
 
<h1>Welcome</h1>
<p>Welcome back, <?php echo $name ?>!</p>
<ul>What would you like to do?
  <li><?php echo link_to('Read the last articles', 'article/read') ?></li>
  <li><?php echo link_to('Start writing a new one', 'article/write') ?></li>
</ul>
 
</body>
</html>
 
 

Template Shortcuts

In templates, a few symfony variables are always available. These shortcuts give access to the most commonly needed information in templates, through the core symfony objects:

  • $sf_context: The whole context object (instance of sfContext)
  • $sf_request: The request object (instance of sfRequest)
  • $sf_params: Parameters of the request
  • $sf_user: The current user session object (instance of sfUser)

The previous chapter detailed useful methods of the sfRequest and sfUser objects. You can actually call these methods in templates through the $sf_request and $sf_user variables. For instance, if the request includes a total parameter, its value is available in the template with the following:

// Long version
<?php echo $sf_request->getParameter('total'); ?>
 
// Shorter version
<?php echo $sf_params->get('total'); ?>
 
// Equivalent to the following action code
echo $this->getRequestParameter('total');
 
 

Code Fragments

You may often need to include some HTML or PHP code in several pages. To avoid repeating that code, the PHP include() statement will suffice most of the time.

Symfony provides three alternative types of intelligent code fragments to replace includes:

  • If the logic is lightweight, you will just want to include a template file having access to some data you pass to it. For that, you will use a partial.
  • If the logic is heavier (for instance, if you need to access the data model and/or modify the content according to the session), you will prefer to separate the presentation from the logic. For that, you will use a component.
  • If the fragment is meant to replace a specific part of the layout, for which default content may already exist, you will use a slot.

Partials

A partial is a reusable chunk of template code. For instance, in a publication application, the template code displaying an article is used in the article detail page, and also in the list of the best articles and the list of latest articles. This code is a perfect candidate for a partial, as illustrated in Figure 7-2.

Figure 7-2 - Reusing partials in templates

Reusing partials in templates

Including a Partial in a Template of the mymodule Module

// Include the myapp/modules/mymodule/templates/_mypartial1.php partial
// As the template and the partial are in the same module,
// you can omit the module name
<?php include_partial('mypartial1') ?>
 
// Include the myapp/modules/foobar/templates/_mypartial2.php partial
// The module name is compulsory in that case
<?php include_partial('foobar/mypartial2') ?>
 
// Include the myapp/templates/_mypartial3.php partial
// It is considered as part of the 'global' module
<?php include_partial('global/mypartial3') ?>
 

Listing 7-8 - The Action Defines a Variable, in mymodule/actions/actions.class.php

class mymoduleActions extends sfActions
{
  public function executeIndex()
  {
    $this->total = 100;
  }
}
 

Listing 7-9 - The Template Passes the Variable to the Partial, in mymodule/templates/indexSuccess.php

<p>Hello, world!</p>
<?php include_partial('mypartial',
array('mytotal' => $total)
) ?>
 

Listing 7-10 - The Partial Can Now Use the Variable, in mymodule/templates/_mypartial.php

<p>Total: <?php echo $mytotal ?></p>
 

Components

In Chapter 2, the first sample script was split into two parts to separate the logic from the presentation. Just like the MVC pattern applies to actions and templates, you may need to split a partial into a logic part and a presentation part. In such a case, you should use a component.

A component is like an action, except it's much faster. The logic of a component is kept in a class inheriting from sfComponents, located in an action/components.class.php file. Its presentation is kept in a partial. Methods of the sfComponents class start with the word execute, just like actions, and they can pass variables to their presentation counterpart in the same way that actions can pass variables. Partials that serve as presentation for components are named by the component (without the leading execute, but with an underscore instead). Table 7-1 compares the naming conventions for actions and components.

Table 7-1 - Action and Component Naming Conventions

Convention

Actions

Components

Logic file

actions.class.php

components.class.php

Logic class extends

sfActions

sfComponents

Method naming

executeMyAction()

executeMyComponent()

Presentation file naming

myActionSuccess.php

_myComponent.php

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐

1Symfony (III): View 2symfony 结合 smarty 及相关的问题 3深入浅出Symfony2 - 结合MongoDB开发LBS应用 4【Chapter 6 Routing】.The Book for Symfony 2.4 第六章 路由(Routing) 5Symfony 6Symfony2.x + EasyUI datagrid Ajax方式实现数据交互 7Symfony 模版快捷变量应用实例