asset()在Symfony Twig模板中返回错误的URL

时间:2013-05-24 03:27:00

标签: symfony stylesheet

我正在学习Symfony框架,但是在将它返回到资源的正确URL方面我遇到了问题。我在我的src / Company / TestBundle / Controller / DefaultController.php文件中创建了一个新的bundle,Company / TestBundle:

<?php

namespace Company\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render('TestBundle:Default:index.html.twig');
    }
}

在src / Company / TestBundle / Resources / views / Default / index.html.twig中:

{% extends "SmallworldBundle:Default:main.html.twig" %}

{%block title %}It's a small world after all!{% endblock %}

{% block body %} It's a small world! {% endblock %}

在src / Company / TestBundle / Resources / views / Default / main.html.twig中:

<html>
<head>
{% block stylesheets %}
<link rel = "stylesheet" href = "{{ asset('css/small.css') }}" type = "text/css" />
{% endblock %}
<title>{% block title %} {% endblock %}</title>
</head>
<body>
{%block body %}{% endblock %}
</body>
</html>

现在,我运行php app / console资产:安装--symlink但是即便如此,生成的代码试图链接到'/css/small.css'而不是文件实际所在的位置,这是src /Company/TestBundle/Resources/public/css/small.css

有人可以解释为什么这不会链接到正确的位置吗?

2 个答案:

答案 0 :(得分:1)

虽然NoScope的answer是一个有效的解决方案,但最好不要对web / bundles / testbundle引入硬依赖。

你应该使用......

{% block stylesheets '@CompanyTestBundle/Resources/public/css/small.css' %}
    <link rel = "stylesheet" href="{{ asset_url }}" type = "text/css" />
{% endblock %}

......相反。

这样,如果您更改资产安装资产的方式,您仍会显示正确的路径。

答案 1 :(得分:0)

您需要添加包名称,如:

{{asset('bundles / testbundle / css / small.css')}}