0

我想在单击某些链接时显示一些图片,但我不知道如何从控制器发送它们,因为每次我都有 src= {{ assets('bundles/fds/...') }}。我该如何解决?

public function getPictureAction() {
        $html  =    '<div id="comment_list_div">';
        $html .=          '<div id="comment_list_div_img">';
        $html .=                '<div id="comment_list_div_im">';
        $html .=                     '<a href=""><img src="{{ asset('bundles/fds/images/Picture.png') }}"/></a>';
        $html .=                 '</div>';
        $html .=          '</div>';
        $html .=          '</div>';


        $return = array( "html" => $html);
        $return = json_encode($return);
        return new Response($return, 200, array('Content-Type'=>'application/json'));

    }
4

1 回答 1

1

执行此操作的正确方法是将您的html代码移动到模板中并在您的操作中呈现它:

在您的控制器中:

use Symfony\Component\HttpFoundation\JsonResponse;

// ...

public function getPictureAction() {

    // load your picture from the db

    $content = $this->renderView(
        'AcmeHelloBundle:Json:JsonResponse.html.twig',
        // pass the picture to your template:
        array('imagePath' => $image->getPath())
    );

    return new JsonResponse(
        $content,
        200,
        array('Content-Type'=>'application/json')
    );
}

还有你的模板:

<div id="comment_list_div">
    <div id="comment_list_div_img">
        <div id="comment_list_div_im">
            {# use the vairable name you passed to this template to acces your image #}
            <a href=""><img src="{{ asset(imagePath) }}"/></a>
        </div>
    </div>
</div>

还要确保您的资产到位:

php app/console assets:install
php app/console assetic:dump --env=dev
于 2013-10-20T22:12:28.227 回答