Search code examples
phpsymfony1components

How should components add JavaScript and CSS in Symfony


My layout.php calls include_javascripts() before my componet could call sfResponse::addJavascript(). Is there a "helper" or a "best practice" to handle this?

Do I have to Seperate the call sfResponse::addJavascript()? I were happy to avoid it.

Here ist my actual workaround:

<head>
  <?php $nav = get_component('nav', 'nav') /* Please show me a better way. */ ?>
  <?php include_javascripts() ?>
  ...
</head>
<body>
  <?php /* include_component('nav', 'nav') */ ?>
  <?php echo $nav ?>
  ...
</body>

Thanks


Solution

  • If your component is always used just move your javascript inclusion into the layout's rendering in your app's view.yml:

    default:
      javascripts: [my_js]
    

    There is no need to separate the JS call when it is always used.

    UPDATE:

    If you must maintain the JS inclusion with the component you can place your component call in a slot before your include_javascripts() call to add it to the stack to be rendered and then include the slot in the appropriate place:

    <?php slot('nav') ?>
    <?php include_component('nav', 'nav'); ?>
    <?php end_slot(); ?>
    <html>
      <head>
        <?php include_javascripts() ?>
        ...
      </head>
      <body>
        <?php include_slot('nav'); ?>
        <?php echo $nav ?>
        ...
      </body>
    </html>