11

我正在尝试优化我的项目以避免发送带有静态资源的 cookie(即:图像、脚本、样式表等)。我的方法是创建一个 static.my-domain.com 域以从那里提供所有没有 cookie 的静态资源。

如何使用资产使用 Symfony2 从该域加载资源?

我正在使用 Symfony 2.1 RC2

4

2 回答 2

4

原来有一个assets_base_urls选项允许您设置资产域。

于 2012-09-01T15:29:23.927 回答
1

我添加了一些 Twig 全局变量来处理这个问题

# config.yml
framework:
    templating:
        engines: ['twig']
        assets_version: 'dev'
        assets_version_format: "%%2$s/%%1$s"
    session:
        cookie_domain:        %session.cookie_domain%
twig:
    globals:
        assets_version: dev
        static_assets_base_url: %static_assets_base_url%
        static_images_base_url: %static_images_base_url%
        static_image: %static_images_base_url%/dev/ # I didn't know how to reference the assets_version, so this is the same value
        static_content: %static_images_base_url%/

# parameters.yml
parameters:
    session.cookie_domain: .myapp.dev
    static_assets_base_url: http://myapp-static.dev
    static_images_base_url: http://myapp-static.dev/path/to/web
  • 对于版本化和编译的 css/js 等,我打印{{ static_assets_base_url ~ asset_url }}.
  • 对于版本化图像等,我打印{{ static_image ~ 'bundles/mybundle/img/icon.jpg' }}.
  • 对于非版本化图像等,我打印{{ static_content ~ 'content/img/upload-123.jpg' }}.

I don't remember exactly why I did this, but it was related to assetic bugs (what a surprise). It just can't handle paths correctly, like sometimes it doesn't add the version, or it does it wrongly.

It will be a pain if you have to modify the assets version manually, so you better have a deployment script ready to do this.

Oh and remember that Assetic won't dump the compiled assets in the specified directories, this is a known issue. So you have to add your own symlinks for these directories.

EDIT

The 'session.cookie_domain' parameter lets you use the same domain and avoid cookies, if your app is in a subdomain. If your app is not using a subdomain, you will have to use a separate domain for the static assets.

于 2012-09-02T16:55:42.270 回答