通过构建所有asset_path值来避免* .js.erb文件 [英] Avoid *.js.erb files by building all the asset_path values

查看:88
本文介绍了通过构建所有asset_path值来避免* .js.erb文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我只想避免使用ERB处理JavaScript文件,以便获得正确的资产路径,例如图像.

So I want to avoid processing JavaScript files with ERB just so I can get a proper asset path to, say, an image.

目前,这似乎很流行:

var myImage = "<%= asset_path('my_image') %>";

var myImage = "<%= asset_path('my_image') %>";

当然,这需要将文件名更改为"* .erb",以便对其进行处理.

Which, of course, requires the filename be changed to "*.erb" so that it'll be processed.

我宁愿将ERB丑陋程度隔离到项目中的某一点,而是制作一个清单文件(例如"assets.js.erb"),该清单文件可计算并提供JavaScript需要的所有资产路径.

I'd much rather isolate the ERB ugliness to one point in my project making a single manifest file (say, "assets.js.erb") that computes and makes available all the asset paths my JavaScript needs.

我当然可以通过逐案解决它来做到:

I can certainly do it WETly by tackling it case-by-case:

ASSETS =
  "my_image": "<%= asset_path('my_image') %>"

window.assetPath = (path) -> ASSETS[path]

但是,我真的只想写一些ERB来遍历所有asset_paths.asset_environment.paths并为我构建一个大对象文字清单,以便我的真实应用程序JavaScript可以放心地调用:

But, I'd really rather just write some ERB to recurse through all of my asset_paths.asset_environment.paths and build a big object literal manifest for me, so that my real application JavaScript can confidently call:

var myImage = assetPath('my_image');

var myImage = assetPath('my_image');

关于(1)是否有更简单的方法错过了我的想法,或者(2)如何完成对asset_path的所有可能有效参数的搜索?

Any ideas on (1) if there's an easier way to do this that I missed, or (2) how I'd accomplish a search of all the potential valid arguments to asset_path?.

推荐答案

一种更简单的方法:

  1. 在.js.erb中获取资产前缀:<%= Rails.configuration.assets.prefix%>.如果需要绝对路径,您还可以获取应用程序URL(从rails获取更为复杂,因此您可以将其硬编码到.js.erb中?)

  1. Get the assets prefix in your .js.erb : <%= Rails.configuration.assets.prefix %>. If an absolute path is needed, you can also get the application URL (it's more complicated to get it from rails, so you can just hardcode it in your .js.erb ?)

如果您使用的是预编译资产,请获取存储在 manifest.yml 中的文件的指纹(位于<%= Rails.configuration.assets.manifest%>) .清单包含一个清单,其中包含您的所有资产及其各自的指纹(文档)

If you are working with precompiled assets, get the fingerprint of your file which is stored in manifest.yml (at <%= Rails.configuration.assets.manifest %>). The manifest contains a list with all your assets and their respective fingerprints (documentation)

让assetPath只是在应用程序URL +前缀之前添加您的图像名称或指纹

Make assetPath just prepending the application URL + prefix to your image name or fingerprint

一个不便之处是您必须指定完整的图像名称(包括扩展名).

An inconvenient is that you have to specify the full image name (included the extension).

这篇关于通过构建所有asset_path值来避免* .js.erb文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆