0

I have an array in php:

<?php

return array(
 'r'      => '16:9',
 'check'            => array(
                            array('w' => 640, 'q' => 70),
                            array('w' => 960, 'q' => 70)
                      ),                            
 'window_height'        => 800
);

I need to get this in my javascript, so I have:

<script>var config = "{{ json_encode(Config::get('conf')) }}";</script>

But im having trouble getting each element out.

Note: {{}} is laravel for echo.

5
  • 2
    "Note: {{}} is laravel for echo" -> Its twig, not laravel Commented Jun 18, 2014 at 17:59
  • Why don't you create a string variable in PHP (json encode stuff) and try echoing the variable alone in your template? Twig does a lot, but there's no reason to offloading everything to Twig Commented Jun 18, 2014 at 18:00
  • "getting each element out"... HOW? your json_encode isn't working? having trouble accessing the config array in JS? Commented Jun 18, 2014 at 18:00
  • Just suggesting but why don't you return a json_encoded version of the array? Something like return json_encode($array). Commented Jun 18, 2014 at 18:01
  • So what problem are you actually having? json_encode() should convert your associative array to an object (with nested arrays in check property) as you desire. Commented Jun 18, 2014 at 18:02

1 Answer 1

1

Assuming there is no additional HTML escaping applied by your template engine, all you have to do is remove the quotes. JSON-encoding takes care of all this for you.

<script>var config = {{ json_encode(Config::get('conf')) }};</script>

You can debug this yourself by viewing the raw output of your PHP script. (Usually "view source" in your browser.)

Now, I don't know Twig, but according to its documentation there may be a better way by using its own JS escaping. Untested obviously, but give this a try:

{% autoescape 'js' %}
    <script>var config = {{ Config::get('conf') }};</script>
{% endautoescape %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.