简体   繁体   中英

converting the elements in an array to a customized string using PHP-Symfony

I am trying to pass the elements in an array to a twig file. After it is passed, the html (in the js) code should look like

var states = ['car','van','bus']

I used the following code to do so using php symfony

/**
 * @Route("/test", name="test")
 */
public function testAction(Request $request)
{
    $products=$this->getDoctrine()->getRepository(products::class)->findAll();
    $pr_name=array();
    foreach ($products as $product){
        $name=$product->getName();
        array_push($pr_name,$name);

    }

    $pr_name2="'".implode("','",$pr_name)."'";
    dump($pr_name2);
    exit;

    return $this->render('typeahead.html.twig', array(
        'pr_name'=>$pr_name2,
    ));

}

My Twig file

<script>
 var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
        var matches, substringRegex;

        // an array that will be populated with substring matches
        matches = [];

        // regex used to determine if a string contains the substring `q`
        substrRegex = new RegExp(q, 'i');

        // iterate through the pool of strings and for any string that
        // contains the substring `q`, add it to the `matches` array
        $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
            }
        });

        cb(matches);
    };
};

var states = [{{ pr_name }}]

$('#the-basics .typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        name: 'states',
        source: substringMatcher(states)
    });

But what I get is this 结果

How to fix this?

Try replacing

var states = [{{ pr_name }}]

with

var states = [{{ pr_name|raw }}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM