Search code examples
ruby-on-railsejsunderscore.js-templating

How can I access Rails asset_path in a JST Underscore template?


I need to access the asset_path of my images from a JST template that's used by my front-end for rendering with Underscore templates.

For instance:

filter_item.jst.ejs

<div class="filter-item">
    <a href="#" class="thumbnail filter-select" data-preset="<%= preset %>">
        <img src="<%= asset_path('balloons.jpg') %>"><br/>
    </a>
</div>

How do I resolve 'asset_path' from my template to use the Rails asset pipeline? At the same time I want to be able to pass in the variable 'preset' from the Underscore template at run-time.

Example:

var rendered = JST["myapp/templates/filter_item"]({preset: "mypreset"});

I expect 'rendered' to contain HTML like so:

<div class="filter-item">
    <a href="#" class="thumbnail filter-select" data-preset="mypreset">
        <img src="/assets/balloons-ASSETHASH.jpg"><br/>
    </a>
</div>

Solution

  • A few months old, but I struggled with this recently myself. Found the answer on the github page for sprockets

    Add the extension .str to your files and you can use ruby/rails methods inside of the string interpolation tags: #{ ... }

    So the above code modified to use string interpolation will work:

    // filter_item.jst.ejs.str
    
    <div class="filter-item">
        <a href="#" class="thumbnail filter-select" data-preset="mypreset">
           <img src="#{ asset_path('balloons.jpg') }"><br/>
        </a>
    </div>
    

    As for the data-preset variable, I'm not familiar enough with how the asset pipeline works to say whether the above method would work for that.