Giter VIP home page Giter VIP logo

skim's Introduction

Skim Build status

Take the fat out of your client-side templates with Skim. Skim is the Slim templating engine with embedded CoffeeScript. It compiles to JavaScript templates (.jst), which can then be served by Rails or any other Sprockets-based asset pipeline.

Install

gem install skim, or add skim to your Gemfile.

Usage

Create template files with the extension .jst.skim. For example, test.jst.skim:

p Hello #{@world}!

In your JavaScript or CoffeeScript, render the result, passing a context object:

$("body").html(JST["test"]({world: "World"}));

Command Line Interface

The CLI allows Skim to be used in Gulp and Grunt workflows, extending the reach of Skim from the Ruby world into the JS/ES/CoffeeScript communities.

Features:

  • Options to output Skim asset and templates separately.
  • Options to assign template function to module.exports, a global function variable, or a global object (keyed by filename, as Sprockets does with its JST object).

Usage: skim [options]

-s, --stdin                      Read input from standard input instead of an input file
-e, --export                     Assign to module.exports for CommonJS require
-n, --node-global                Use Node.js global object for global assignments
    --jst                        Assign to global JST object keyed by truncated filename
    --assign variableName        Assign to a global variable
    --assign-object objectName   Assign to a global object keyed by truncated filename
    --asset-only                 Output only the Skim preamble asset
    --omit-asset                 Omit Skim preamble asset from output
    --trace                      Show a full traceback on error
-o, --option name=code           Set skim option
-r, --require library            Load library or plugin
-h, --help                       Show this help message
-v, --version                    Print version number

Caveats

Skim is an early proof-of-concept. Some Slim features are still missing:

  • Skim does not currently support embedded engines. Being a client-side templating languages, it will only be able to support embedded engines with a client-side implementation.
  • Skim does not currently support HTML pretty-printing (Slim's :pretty option). This is low priority, as pretty-printing is even less important client-side than server-side.
  • Skim does not currently support backslash line continuations.

Language reference

Skim supports the following Slim language features:

  • doctype declarations (doctype)
  • HTML Comments (/!) and conditional comments (/[...])
  • static content (same line and nested)
  • dynamic content, escaped and not (= and ==)
  • control logic (-)
  • string interpolation, escaped and not (#{} and #{{}})
  • id and class attribute shortcuts (# and .)
  • attribute and attribute value wrappers
  • logic-less (sections) mode

Several Coffee/JavaScript considerations are specific to Skim:

  • When interpolating the results of evaluating code, Skim will replace null and undefined results with an empty string.
  • You will typically want to use the fat arrow => function definition to create callbacks, to preserve the binding of this analogously to how self behaves in a Ruby block.

The Context Object

The context object you pass to the compiled template function becomes the value of this inside your template. You can use CoffeeScript's @ sigil to easily access properties and call helper methods on the context object.

Escaping and Unescaping

Like Slim, Skim escapes dynamic output by default, and it supports the same == and #{{}} syntaxes for bypassing escaping. In addition, the special safe method on the context object tells Skim that the string can be output without being escaped. You can use this in conjunction with escape context method to selectively sanitize parts of the string.

For example, given the template:

= @linkTo(@project)

you could render it with the following context:

JST["my_template"]
  project: { id: 4, name: "Crate & Barrel" }
  linkTo: (project) ->
    url  = "/projects/#{project.id}"
    name = @escape project.name
    @safe "<a href='#{url}'>#{name}</a>"

to produce:

<a href='/projects/4'>Crate &amp; Barrel</a>

The Skim Asset

By default, all you need to do to start using Skim is add it to your Gemfile. Skim will embed a small amount of supporting code in each generated template asset. You can remove this duplication by manually including Skim's asset, and setting Skim's :use_asset option to true.

In Rails, this can be done by adding the following to application.js:

//= require skim

And the following in an initializer:

Skim::Engine.default_options[:use_asset] = true

Skim templates also support dependency injection for the Skim asset, instead of using a global Skim variable. Example in Node.js:

var Skim = require('./skim_asset_module.js')
var template = require('./template_module.js');
console.log(template({Skim: Skim, first_name: 'Dave', last_name: 'Smith'}));

License (MIT)

Copyright (c) 2012 John Firebaugh, (c) 2015 AppJudo Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Special Thanks

  • John Firebaugh, for creating Skim
  • Andrew Stone, for Slim
  • Magnus Holm, for Temple
  • Daniel Mendler, for maintenance of Slim and Temple

skim's People

Contributors

akzhan avatar donschado avatar erol avatar gkopylov avatar grossws avatar jfirebaugh avatar kossnocorp avatar pavelkomiagin avatar steverandy avatar svicalifornia avatar yury avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

skim's Issues

Templates path common prefix.

Imagine you put all your Skim templates to app/assets/javascripts/backbone/some/directory/my/templates/foo/bar/*.jst.skim

So, on the client, all compiled templates will have JST object keys containing this ridiculously long path.

It would be nice to have a setting that allows to specify template path common prefix. So you can set it to backbone/some/directory/my/templates/foo/bar for instance and have your JST object keys drop this part of the path.

If there is such setting already, it would be nice to put it into README, so people would know about it. :)

Could skim support slim version > 2 ?

Right now when I want to installed it I get the following error

Bundler could not find compatible versions for gem "slim":
  In Gemfile:
    skim (>= 0) ruby depends on
      slim (~> 1.1.0) ruby

    slim (2.0.0.pre.6)

Still being maintained?

@jfirebaugh this is a really cool project, and I'm considering using it in a site I am working on.

Is it still being developed/maintained? Are there any caveats that you would mention in considering this for a production site?

Sorry if this is not the place for a question like this, please let me know if there is a better place. And again, cool project! thanks.

Templates with supportive code are broken.

Here's how compiled template looks like right now (use_asset is false):

(function() {
  this.JST || (this.JST = {});
  this.JST["my_template"] = (function() {

    return function(context) {
      if (context == null) {
        context = {};
      }
      this.Skim = {
        access: function(name) {
          var value;
          value = this[name];
          if (typeof value === "function") {
            value = value.call(this);
          }
          if (value === true) {
            return [this];
          }
          if (value === false || !(value != null)) {
            return false;
          }
          if (Object.prototype.toString.call(value) !== "[object Array]") {
            return [value];
          }
          if (value.length === 0) {
            return false;
          }
          return value;
        },
        withContext: function(context, block) {
          var create;
          create = function(o) {
            var F;
            F = function() {};
            F.prototype = o;
            return new F;
          };
          context = create(context);
          context.safe || (context.safe = this.safe || function(value) {
            var result;
            if (value != null ? value.skimSafe : void 0) {
              return value;
            }
            result = new String(value != null ? value : '');
            result.skimSafe = true;
            return result;
          });
          context.escape || (context.escape = this.escape || function(string) {
            if (string == null) {
              return '';
            }
            if (string.skimSafe) {
              return string;
            }
            return this.safe(('' + string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/\//g, '&#47;'));
          });
          return block.call(context);
        }
      };
      return Skim.withContext.call({}, context, function() {
        var _buf;
        _buf = [];
        _buf.push("<div id=\"my_div\"></div>");
        return _buf.join('');
      });
    };

  }).call(this);;
}).call(this);

If you look carefully, it tries to define Skim on the current this context but later call it as a global variable. So if you actually try to run something like JST['my_template']() you'll get ReferenceError: Skim in undefined. Also, you'll get JST.Skim defined, which is probably unwanted behavior here.

Templates do not compile

I've put *.jst.skim templates into app/assets/javascripts/templates
For example, chat.jst.skim.
I've added

config.assets.precompile += ['templates/*.skim']

to my config/application.rb

It works seemlessly in Dev, but I can't compile them with
RAILS_ENV=production rake assets:precompile
None of these templates are compiled.

Could someone help me? I have no idea what I do wrong.

Add server-side evaluation

One occasionally wants to use Rails helper methods (especially asset and route helpers) in client-side templates. Existing solutions are ugly.

The fact that Skim is implemented in Ruby and compiles server-side affords a unique solution: server-side evaluation within the language. I'm thinking of adding two new sigils: ~ and , server-side analogs of - and =. (Think of ~ as a sideways S, for Server.) Within these sigils, you write Ruby instead of CoffeeScript. You are responsible for keeping your template logic simple enough that writing in two different embedded languages doesn't become confusing.

Example:

a href≈my_path
  ≈ image_tag "logo.png"

my_path and image_tag would be evaluated at compile time, generating the equivalent of:

a href="/my/path"
  img src="/assets/logo.png"

Maybe ≈ isn't the best choice, as it's hard to type and forces the encoding issue. But you get the idea.

How to use regex expression in control logic?

When I try to do:

- whatever = "hello world".replace(/ /g, '_')

I get

Uncaught Error: ExecJS::RuntimeError: SyntaxError: [stdin]:57:38: unexpected /
  (in /.../my_file.jst.skim)

There is a problem with / - ideas how to workaround this other then extracting that logic outside the .skim template?

Versions:
Skim: 0.9.3
Slim: 2.0.2

Iterating and working with collections

Hello,

I have a trouble with iterating over an array. I have an array of objects, that have other objects and i want to get this value in each element of array and past it in link. In ruby i will use this code:

- if @attachments
  - @attachments.each do
    a href="#{@attachments.file.url}" "#{@attachments.file_name}"

So how I can handle it in skim? I cant find the way.

Rails 6 configuration

Hi,
trying to implement SKIM in my rails 6 project. Can't figure out, where should I put .jst.skim files or how correctly render them.
Tried to create javascript/templates folder and store files there, calling them with JST["templates/file"]({data: data}), but caught ReferenceError: JST is not defined.
Requiring them form application.js like require "templates/file" or require "templates/file.jst.skim" also failed.
Are there any settled sollution for rails 6?

ExecJS::RuntimeError - SyntaxError: unexpected LOGIC

Getting the above error from this line of my template.

- if result.get("price")
  .label class=result.get("price").toLowerCase() = result.get("price")

Trying to trace the error from the coffeescript source and it seems the error is from this line.

_temple_coffeescript_attributeremover1.push(_temple_html_attributemerger1.reject(&:empty?).join(" "))

Sprockets register_engine deprecated

Hello there!

I'm using the skim gem to convert hamljs templates to slim using the .jst.skim extension. It works perfectly but Sprockets as of version 3.7.0 deprecated the register_engine call in favor of a different approach using register_mime_type and either register_compressor or register_transformer.

It shows that they added a deprecation notice in the 3.7.0 section in the release notes

This is the exact error I'm getting:

DEPRECATION WARNING: Sprockets method `register_engine` is deprecated.
Please register a mime type using `register_mime_type` then
use `register_compressor` or `register_transformer`.
https://github.com/rails/sprockets/blob/master/guides/extending_sprockets.md#supporting-all-versions-of-sprockets-in-processors
 (called from <top (required)> at /Users/myusername/.rvm/gems/ruby-2.3.0/gems/skim-0.10.0/lib/skim/sprockets.rb:3)

From what I can find, there is no simple way to get around this deprecation warning due to the fact that version 3.7.0 deprecates the functionality but still requires you to use it :|

I would write something along these lines to fix the registering issue, however the Skim::Template class cannot handle Sprockets 4 yet (which is still in beta at the time of writing). Either way it might give you some inspiration!

if Sprockets.respond_to?(:register_engine)
  args = ['.skim', Skim::Template]
  if Sprockets::VERSION.start_with? '3'
    args << {silence_deprecation: true, mime_type: 'text/skim'}
  end

  Sprockets.register_engine *args
else
  Sprockets.register_mime_type 'text/skim', extensions: ['.skim', '.jst.skim']
  Sprockets.register_transformer 'text/skim', 'application/javascript', Skim::Template
end

Replicating this issue should be simple.

In a fresh Rails (5, using sprockets >= 3.7.0) app,

Gemfile

gem 'skim'
gem 'sprockets', '>= 3.7.0'

Run the bundle or bundle install command
Restart rails server (ctrl+c to stop rails s to start)

The message should appear when starting the server, if not try creating a template

Sprockets 2.0 support

Just need to force autoloading by referencing Sprockets::Engines before calling #register_engine.

Problem with my template

Sorry to bother you, but I am not sure what I am doing wrong:

I am having a skim template with the following content:

dl
  dt= I18n.t('images_show.meta.file_created_at')
  dd= if @image.file_created_at then "-" else  I18n.l(@image.file_created_at, :format => :long)

And I get: An error occurred compiling assets: Error: Parse error on line 12: Unexpected '{'
The if-then-else clause should be valid coffeescript... so I thought it should work....

Uncaught ReferenceError: JST is not defined

I've caught JST is not defined error in a browser console after new project creation. Just wanted to have some experiments with skim.

Gemfile

gem 'rails', '~> 5.1.2'
gem 'sqlite3'
gem 'puma', '~> 3.7'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'slim-rails'
gem 'jquery-rails'
gem 'slim-rails'
gem 'skim'
gem 'therubyracer'

application.js

//= require jquery
//= require jquery_ujs
//= require rails-ujs
//= require turbolinks
//= require skim
//= require_tree .

books.coffee file

skim = ->
  $("#greeting").html JST["books"]({world: "World"})

$(document).ready(skim)

books.jst.skim in the same location where books.coffee files located
p Hello #{@world}!

I would appreciate any advise on how to solve the issue and add skim to my application correctly?

Regards,
Sergey

`unexpected &` error

With version 0.10.0 I have this error (unexpected &) when try to load a page with js which use this template

.some_class class="#{@status}"
  span=@message

I found that the problem in this part class="#{@status}
But this code works perfect with version 0.9.3
Not sure is it bug or I do something wrong. If it's OK, then could you tell me how I can implement dynamic classes?

rails 4.2 and slim-rails

Bundler could not find compatible versions for gem "slim":
In Gemfile:
skim (>= 0) ruby depends on
slim (<= 2.0.1, >= 2.0.0) ruby

slim-rails (>= 0) ruby depends on
  slim (3.0.0)

Production issue with the Skim asset

If you add skim to the asset group in your Gemfile and include an initializer with the following:

Skim::Engine.default_options[:use_asset] = true

as stated in the readme, all works great in development. When you deploy to production however, you get an unintialized constant Skim as the asset group is not used (specifically when deploying to Heroku).

The quick fix is to move the skimgem reference out of the asset group. Is that the best option?

Possible global scope issue?

I have one template inadvertently calling the Skim.withContext method of another template. It seems as though this should not happen, but it very definitely is. Any chance the call to Skim.withContext can be changed to be more specific? I have many templates and it's only happening with these two.

Splat operator (conditional attributes) support?

EDIT: Discovered the Splat operator, re-writing...

I'm trying to set up a conditional attribute... for example, I want the result to be one of the two following:

<a>Lotsa content</a>

or

<a href="some/link">Lotsa content</a>

The condition would be whether or not the href exists. So the skim pseudo-code would be something like this:

a *( if @url then { href: @url } else {} )
  Lotsa content

I know that doesn't work, obviously, but I can't find any way to do this in skim. Slim supports it via their splat operator. The "correct" coffeescript version would be like the example just above. In ruby/slim it's a *( @url ? { href: @url } : {} )

I'd rather not do this:

- if @url
  a href='#{@url}'
    Lotsa content
- else
  a
    Lotsa content

Because "Lotsa content" is a ton of code duplication. I also don't want the href in the a tag, because clicking on an empty href causes the page to reload. I could make the link do nothing when clicked on if there's no href, but it would be much easier just to omit the href and let that behavior happen naturally.

Would it be possible to implement the splat operator?

- Evaluation Does Not Work

Code:

- if true
  a hey                     

Result:

Generator supports only core expressions - found [:html, :tag, "a", [:html, :attrs], [:multi, [:newline], [:html, :tag, "hey", [:html, :attrs], [:multi, [:newline]]]]]
  (in /project_path/app/assets/templates/test.jst.skim)

Uncaught ReferenceError: JST is not defined

What is JST and where to find it?

In Rails project:

# app/assets/javascripts/application.coffee
#= require skim
JST['index']
# Gemfile
gem 'skim', git: 'https://github.com/jfirebaugh/skim'
gem 'rails', '4.2.2'

Uncaught ReferenceError: Skim is not defined

I'm having a hard time getting skim to render a template in a Rails app with the asset pipeline. I'm getting the above error. I originally did the template with ECO and it worked fine. Trying to convert it to skim and it's failing.

Here are the files in question:

https://gist.github.com/2775235

Any suggestions are appreciated. Thanks.

Conflicting slim versions with slim-rails and skim 0.8.5

I can't apply the 0.8.5 fix because of a conflict.

Bundler could not find compatible versions for gem "slim":
  In Gemfile:
    skim (>= 0.8.5) java depends on
      slim (<= 1.2.0) java

    slim-rails (>= 0) java depends on
      slim (1.3.0)

Syntax Error: Unexpected &

After updating, I found out that doing this:

- class_name = 'ruby'
.hello class=class_name Hello Ruby!

Would throw an Syntax Error: Unexpected &
class_name must not be static, it's a strange case that has to do with attribute merging.

I found that the commit '187084f' to be the culprit. The exact change that causes this is:

+    html :AttributeMerger

I'm not actually sure what this lines does as I haven't dealt with Temple before, but commenting that line fixes the problem for me.

I fixed that in my fork, and also added two tests to verify it.
This is the fork: https://github.com/bartosz-zawada/skim

Move JS helpers to separate file

Maybe it is better to move _access, safe and other from template.rb to separate file and not pollute small templates?

It can be as an option for skim engine.
User can simply all helpers via require 'skim' in his application.js

Not working

I have included the skim gem as instructed.

using //= require skim results in a missing file error

adding Skim::Engine.default_options[:use_asset] = true results in NameError: uninitialized constant Skim

Seems a bit odd to me. Any insights?

<name>.jst.js?

So when I include a skim template, my system searches for name.jst.js but the file is typically only available at name.jst or name.js.

As a hack, I'm naming my templates name.jst.js.skim which is pretty meh.

How to iterarate json object?

I can't seem to iterate on json object, for...in does not iterate, or maybe I just don't know how to do it

- for key in { "key1": "value1", "key2": "value2" }
  = key  // doesn't work
  p item // also doesn't work

for...in works with array, but not with json object

Optimization on browsers

I made a jsperf test to compare skim and hogan.
http://jsperf.com/skim

The result, skim is about 80% slower than hogan.
I tried to use string buffer instead of array buffer.
It helped a little bit. But nothing significant.

Are there any other ways we can optimize skim rendering on browsers?

Uncaught ReferenceError: variable is not defined

Hello!
I'm trying to use JST templates in my rails project but i'm not able to do one simple thing. I'm trying to pass a variable to my template, here is my code:

scripts.js.coffee

$('body').append( JST['single_product']( product: 'Product name' ) )
# ... or ...
$('body').append( JST['single_product']( { product: 'Product name' } ) )

single_product.jst.skim

p= @product

That code gives me an error in console saying Uncaught ReferenceError: product is not defined. I've seen a lot of tutorials on how to use JST and my code looks exactly the same. Does anyone knows what can be wrong in here?

Thanks in advance.

SO: http://stackoverflow.com/questions/19927668/jst-undefined-variable-error

Unexpected token return

Screenshot illustrates the problem:

$ cat Gemfile.lock | grep sprockets
      sprockets (~> 2.0.3)
      sprockets
    sprockets (2.0.3)
  sprockets (~> 2.0.3)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.