简体   繁体   中英

How can you pass a parameter from an action to the layout in Symfony

The global layout.php file contains the tags for each page:

<body> 
    <?php echo $sf_content ?>
</body>

But for all my inner HTML pages of the site, a class is applied to the body tag:

 <body class="inner-page"> 
    <?php echo $sf_content ?>
 </body>

How can I pass in a class to the layout from different templates?

in your layout.php

<body <?php if (!include_slot('body_id')): ?>id="default"<?php endif; ?>>

in your templates :

<?php slot('body_id') ?>id="bla"<?php end_slot(); ?>

or

<?php slot(
  'body_id',
  sprintf('id="%s"', $sf_params->get('module')))
?> 

Here is the solution I used with Symfony 1.2+

Use setSlot() in the action:

$this->getResponse()->setSlot('home_page', 'yes');

Then use get_slot() in the Layout:

<body class="<?php echo has_slot('home_page') ? 'home-page' : 'inner-page' ?>">

sfConfig::set('name_here', $variableHere);
$variable = sfConfig::get('name_here');

I use this a lot. Use this anywhere on the code.

In most MVC frameworks, you access variables in the layout the same way you access them in the view files.

So, if you did something like $this->view->my_data=10; in the control. You can access it in the layout by: echo $this->my_data.

This was pseudo code, adjust it to the symphony way.

I'm 90% sure that you do this the same way you'd do it from a regular view file. So as long as you set the variable in the action, it should be accessible from the layout.php file.

In your action:

$this->body_class = "xxx";

In layout.php

<body class="<?php echo $body_class?>"> 

Be sure to run some checks to make sure $body_class is set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM