繁体   English   中英

预编译application.js资产

[英]Precompiling application.js assets

如何在我的application.js中获得此代码,以便可以预编译此处使用的图像? 我应该使用哪种Rails助手?

    $(document).ready(function(){
    $(".imgthumb").click(function(){
        $(".thumbnailcurrent").addClass("thumbnails");
        $(".thumbnails").removeClass("thumbnailcurrent");
        $(this).addClass("thumbnailcurrent");
        $(this).removeClass("thumbnails");

        var img=($(this).attr("data-id"));

        if (img==1) {

         $('.imgbig').html("<%= asset_path src: 'flappy1.jpg', height: '275', width: '391' %>");
        } else if (img==2) {

         $('.imgbig').html("<%= asset_path src: 'flappy2.jpg', height: '275', width: '391' %>");
        } else if (img==3) {

         $('.imgbig').html("<%= asset_path src: 'flappy3.jpg', height: '275', width: '391' %>");
        }


});

    });

位于公共/资产路径中的预编译图像? 为什么不直接使用此路径?

您无法通过url访问资产:

'/assets/images/flappy1.png' 

因为在生产环境中,您会遇到以下情况:

'/assets/images/flappy1-b3bb250d5300736006c894.png'

它们之间的符合性表位于清单文件中,该文件会自动生成。

但是,直接使用清单文件不是一个好主意,因为其中包含许多无关的数据。

通常,您有两个选择:

  1. 用Erb预处理程序包装您的JavaScript,以访问

    <%= asset_path(path/to/asset.jpg) %>助手。

  2. 或更多美容解决方案: gem'js_assets' ,可以解决您的问题。

gem安装后,您需要包括JavaScript帮助器:

// app/assets/javascripts/application.js

//= require app_assets

符合性表将存储在window.project_assets变量中。

asset_path javascript的helper方法接收到您资产的逻辑路径,并在给定存在环境的情况下返回相对路径:

var path = asset_path('images/flappy1.jpg')
// the function will return for development:
// /images/flappy1.jpg
// and for production
// /assets/images/flappy1-b3bb250d5300736006c894.jpg

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM