Skip to content

hlascelles/knockout-assets

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Knockout Assets

Knockout Assets is a Rails gem that generates full asset URL paths for assets in the asset pipeline. It also supplies simple bindings for using assets in Knockout templates. This makes it very useful for applications that use Knockout and CDNs.

Usage

Install:

gem 'knockout-assets'

Add the loader in yout application.html.erb:

<%= knockout_assets %>

Then use in a template:

<img data-bind="img: 'person.gif'">

Why?

Asset URLs change depending on how they are served up. In production, assets coming from a CDN have a URL generated at compile time. The standard Rails way of solving this is to use an image_tag, which renders the right URL. However, since Knockout templates are rendered client side, they don't have access to this method, unless the templates are generated in the first place using erb or haml.

Using Knockout Assets has three advantages over using a standard image_tag in knockout templates.

  • The knockout templates files need not be processed on the server side at all. This means that testing them (for example with Jasmine) becomes possible.
  • The templates may be served up from a CDN using Knockout.js-External-Template-Engine.
  • The images are preloaded by default so templates render with the correct layout instantly (but this can be optionally disabled).

Options

Include/Exclude some images using a regex

<%= knockout_assets(include: /.*\.(png|gif|jpg|jpeg|bmp|svg)/) %>

or

<%= knockout_assets(exclude: /im.*\//) %>

Or use both (exclude wins).

Disable preloading images

<%= knockout_assets(preload: false) %>

License

MIT License.

About

A rails gem to provide CDN hashes of assets to knockout bindings

Resources

Stars

Watchers

Forks

Packages

No packages published