从控制器到jquery的图片网址[Symfony 2]

时间:2013-10-20 21:08:11

标签: php ajax symfony

我希望在点击某些链接时显示一些图片,但我不知道如何从控制器发送它们因为我每次都有src = {{asset('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'));

    }

1 个答案:

答案 0 :(得分: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