簡體   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