dongqiao5573 2014-06-24 04:40
浏览 41
已采纳

Symfony2:如何在视图模板内的函数中获取资产的URL

As documented here I can read my image files in view by using following code.

<img src="<?php echo $view['assets']->getUrl('images/logo.png') ?>" alt="Symfony!" />
////  This outputs the image

or I can also do

<?php 
    echo $view['assets']->getUrl('images/logo.png'); 
    // echoes --->  /assets/images/logo.png
?>

However, my views are much complex and I want to divide different sections of view in functions. So when I write the above code in a function, it doesn't work.

function one(){
    echo $view['assets']->getUrl('images/logo.png'); 
}
one();
Notice: Undefined variable: view in ....\Resources\views\Section\splash.html.php on line 12

Fatal error: Call to a member function getUrl() on a non-object in ....\Resources\views\Section\splash.html.php on line 12

Can someone please guide me how can I get this to work?


This is my full view file.

<?php
echo $view['assets']->getUrl('images/logo.png') . "<br><br>";

function one(){
    echo $view['assets']->getUrl('images/logo.png') . "<br><br>";
}
one();
?>
<img src="<?php echo $view['assets']->getUrl('images/logo.png') ?>" alt="no image" />

This is how I am calling the view from my controller

return $this->render('MySimpleBundle:Section:splash.html.php');
  • 写回答

2条回答 默认 最新

  • dtzk85937 2014-06-24 08:11
    关注

    The function "one()" has his own variable scope, so you have to pass the url into the function http://php.net/manual/en/language.variables.scope.php

    function one($url)
    {
        echo $view['assets']->getUrl($url) . "<br><br>";
    }
    

    anyway, in my opinion you should use simply:

    <img src="<?php echo $view['assets']->getUrl('images/logo.png') ?>" alt="Symfony!" />
    

    to render the image, if your view gets to complex, it is may the right time to switch to a powerful templating engine like twig

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?