koalabruder
koalabruder

Reputation: 2904

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

Upvotes: 4

Views: 11704

Answers (3)

nortron
nortron

Reputation: 3891

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>

Upvotes: 3

Tom
Tom

Reputation: 30698

From: http://www.symfony-project.org/book/1_2/07-Inside-the-View-Layer

File Inclusion Configuration

// In the view.yml

indexSuccess:
  stylesheets: [mystyle1, mystyle2]
  javascripts: [myscript]

// In the action

$this->getResponse()->addStylesheet('mystyle1'); 
$this->getResponse()->addStylesheet('mystyle2'); 
$this->getResponse()->addJavascript('myscript');

// In the Template

<?php use_stylesheet('mystyle1') ?>
<?php use_stylesheet('mystyle2') ?>
<?php use_javascript('myscript') ?>

Upvotes: 11

timmow
timmow

Reputation: 3625

You may have to disable the sfCommonFiter which is now deprecated. The common filter automatically adds css / js into the layout.

Once you have done this, you can move the include_javascripts call anywhere within the layout.php file, below the include_component('nav', 'nav') call

Upvotes: 0

Related Questions