You already know that there is a total decoupling between an action name and the URL used to call it. So if you create a link to
anotherAction in a template as in Listing 4-10, it will only work with the default routing. If you later decide to change the way the URLs look, then you will need to review all templates to change the hyperlinks.
Listing 4-10 - Hyperlinks, the Classic Way
<a href="/myapp_dev.php/mymodule/anotherAction?name=anonymous"> I never say my name </a>
To avoid this hassle, you should always use the
link_to() helper to create hyperlinks to your application's actions. Listing 4-11 demonstrates the use of the hyperlink helper.
Listing 4-11 - The
<p>Hello, world!</p> if ($hour >= 18): <p>Or should I say good evening? It is already echo $hour .</p> endif; echo form_tag('mymodule/anotherAction') echo label_for('name', 'What is your name?') echo input_tag('name') echo submit_tag('Ok') echo link_to('I never say my name','mymodule/anotherAction?name=anonymous') </form>
The resulting HTML will be the same as previously, except that when you change your routing rules, all the templates will behave correctly and reformat the URLs accordingly.
link_to() helper, like many other helpers, accepts another argument for special options and additional tag attributes. Listing 4-12 shows an example of an option argument and the resulting HTML. The option argument is either an associative array or a simple string showing
key=value couples separated by blanks.
Listing 4-12 - Most Helpers Accept an Option Argument
// Option argument as an associative array echo link_to('I never say my name', 'mymodule/anotherAction?name=anonymous', array( 'class' => 'special_link', 'confirm' => 'Are you sure?', 'absolute' => true )) // Option argument as a string echo link_to('I never say my name', 'mymodule/anotherAction?name=anonymous', 'class=special_link confirm=Are you sure? absolute=true') // Both calls output the same => <a class="special_link" onclick="return confirm('Are you sure?');" href="http://localhost/myapp_dev.php/mymodule/anotherAction/name/anonymous"> I never say my name</a>
Whenever you use a symfony helper that outputs an HTML tag, you can insert additional tag attributes (like the
class attribute in the example in Listing 4-12) in the option argument. You can even write these attributes in the "quick-and-dirty" HTML 4.0 way (without double quotes), and symfony will output them in nicely formatted XHTML. That's another reason why helpers are faster to write than HTML.
Note Because it requires an additional parsing and transformation, the string syntax is a little slower than the array syntax.
Like the form helpers, the link helpers are numerous and have many options. Chapter 9 will describe them in detail.