简体   繁体   English

如何将参数从动作传递到Symfony中的布局

[英]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: 全局layout.php文件包含每个页面的标记:

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

But for all my inner HTML pages of the site, a class is applied to the body tag: 但是对于我网站的所有内部HTML页面,都会将一个类应用于body标记:

 <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 在你的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+ 这是我与Symfony 1.2+一起使用的解决方案

Use setSlot() in the action: 在操作中使用setSlot():

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

Then use get_slot() in the Layout: 然后在布局中使用get_slot():

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

sfConfig::set('name_here', $variableHere); sfConfig :: set('name_here',$ variableHere);
$variable = sfConfig::get('name_here'); $ 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. 在大多数MVC框架中,您可以像在视图文件中访问变量一样访问布局中的变量。

So, if you did something like $this->view->my_data=10; 所以,如果你做了类似$ this-> view-> my_data = 10的事情; in the control. 在控制中。 You can access it in the layout by: echo $this->my_data. 您可以通过以下方式访问布局: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. 我90%肯定你这样做是从普通视图文件中这样做的。 So as long as you set the variable in the action, it should be accessible from the layout.php file. 因此,只要您在操作中设置变量,就应该可以从layout.php文件中访问它。

In your action: 在你的行动中:

$this->body_class = "xxx";

In layout.php 在layout.php中

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

Be sure to run some checks to make sure $body_class is set. 一定要运行一些检查以确保设置$ body_class。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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