开发者

Symfony: Write Content to Head

Is there a reasonably elegant means of writing a simple block of JS to the head of a Symfony layout?

I have a Page module whose showSuccess template is aware of how many widgets it has to display. I need to communicate that number to an external JS file included via use_javascript(). The only way I know to do it with any simplicity is to set a global JS variable 开发者_运维技巧in the rendered content that can be read by the external source file.

I've used the same technique for other path values that are knowable by the layout, but in this case only the page itself knows that value. I can't find a way to write a simple line of JS to the head. I've tried this:

<?php echo javascript_tag(); ?>
  var c_widgets = <?php echo count( $widgets ); ?>
<?php echo end_javascript_tag(); ?>

Unfortunately, it writes directly to the page content and I'd like to avoid doing that. I can do this quite easily with CakePHP and Rails, but I haven't been able to find an analogous solution for Symfony.

UPDATE

In accordance with TheGrandWazoo's answer below, here's what I finally did:

# showSuccess.php
<?php use_helper( 'JavascriptBase' ) ?>

<?php slot( 'scripts_for_head' ) ?>
  <?php echo javascript_tag(); ?>
    var c_widgets = <?php echo count( $widgets ); ?>
  <?php echo end_javascript_tag(); ?>
<?php end_slot(); ?>

# layout.php
<?php include_slot( 'scripts_for_head' ); ?>

So far it's working beautifully.


Use a slot in your template which you can fill from your action/component with a javascript tag is the only solution that comes to mind at the moment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜