What's the symfony way to set a javascript variable?
&开发者_如何学Golt;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?
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.
To implement this in unobstrusive manner I'd recommend to use use_dynamic_javascript
helper.
this is twig excample you may use php.
{% if value %}
<script type="text/javascript">var name="{{ value }}";</script>
{% endif %}
if your script won't work most of the mistakes are ( value is defined after adding main script), or ( you may var same variable in the main script it would bug your source. )
and if you need paste many variables you may use for. like this
{% if js_items %}
<script type="text/javascript">
{% for item in js_items %}
var {{ item.name }} = "{{ item.value }}";
{% endfor %}
</script>
{% endif %}
精彩评论