Avoid *.js.erb files by building all the asset_path values

后端 未结 3 1501
無奈伤痛
無奈伤痛 2021-02-04 04:51

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

Currently, this seems like the popular approach:

3条回答
  •  独厮守ぢ
    2021-02-04 05:18

    It depends on the context of where this image is used.

    Use Case 1: The image is decorative and needs to be dynamically swapped. Example: Spinner, while data is loading. In this case, I refer to is in my sass and java script.

    .spinner
       background-image: url(image_path("spinner.png"))
    

    Then I would operate with classes in java script and not images.

       $.addClass('spinner')
    

    Use Case 2: Image is part of an object.

    There are many situations, when an image actually belongs to a object. In this case, I create a json file, which stores the data and the image reference like this. Then I use erb to unwrap the image reference - my_object.json.erb:

     {
        "icon" : "<%=image_path("icons/my_icon.png")%>",
        "label":"My label",
        "description":"My description"
     }
    

    Use case 2 requires more work on javascript side to load the json files, but it opens very powerful extensibility options.

    Asset pipeline handles both cases famously.

提交回复
热议问题