views:

180

answers:

2
<script type="text/javascript">var name="value";</script>

I need it to be executed before another file included by use_javascript('name.js');

How to do it in symfony?

+2  A: 

You could do it any number of ways

let's say, in your action method, you add a template variable like so

$this->jsVar = 'foo';

Then, in your template file(s)

echo javascript_tag( 'var name="' . $jsVar . '";' );

or

<script type="text/javascript">
  var name='<?php echo $jsVar; ?>';
</script>

EDIT

Ok, based on your specific needs, you'll need to do a few things. First, look at your page template (the one located in apps/app-name/templates - you should see a line that looks like this

<?php include_javascripts(); ?>

That's the function that takes all javascript resources defined in view.yml files or those included by the use_javascript() helper and prints them to the page.

So our goal, then, is to put a javascript block in front of where all the other scripts are included (and by in-front, I mean appearing first in source-order)

To solve this in a somewhat flexible manner, let's use a slot. Modify the above line in your page template to look like this

<?php
  if ( has_slot( 'global_js_setup' ) )
  {
    include_slot( 'global_js_setup' );
  }
  include_javascripts();
?>

Then, in your action method

sfLoader::loadHelpers( 'Asset' );
$this->getResponse()->setSlot(
    'global_js_setup',
  , javascript_tag( 'var name="value";' );
);

You could extend this idea by using component slots if you wanted to.

Peter Bailey
I need it to be executed before another file included by `use_javascript('name.js');`
Ah, I see what you're getting at. I'll update my answer in a sec
Peter Bailey
A: 

To implement this in unobstrusive manner I'd recommend to use use_dynamic_javascript helper.

develop7
How to enforce it to appear before other javascript files are included?
Second parameter of `use_javascript` (and `use_dynamic_javascript` as well) helper is "`position`". As we can see from `sfWebResponse::$position`, valid positions are "`first`", "" (empty string) and "`last`" (instead we can use `sfWebResponse::FIRST`, `sfWebResponse::MIDDLE` or `sfWebResponse::LAST`). So, to enforce them appear before other files, you have to put them into "first" "slot" while others are put to "middle", or into "middle" while others are put "last" one.
develop7
Oh,seems `has_slot` is more convenient here...
Of course it's more convenient, but it makes much easier to "shoot your own leg" with it.
develop7