GithubHelp home page GithubHelp logo

concordusapps / grunt-haml Goto Github PK

View Code? Open in Web Editor NEW
41.0 4.0 28.0 436 KB

Process HAML templates to precompiled JavaScript or rendered HTML.

Home Page: https://npmjs.org/package/grunt-haml

License: MIT License

JavaScript 100.00%

grunt-haml's Introduction

grunt-haml Build Status

Process HAML templates to precompiled JavaScript or rendered HTML.

Getting Started

If you haven't used grunt before, be sure to check out the Getting Started guide, as it explains how to create a gruntfile as well as install and use grunt plugins. Once you're familiar with that process, install this plugin with this command:

npm install grunt-haml --save-dev

Haml task

Run this task with the grunt haml command.

This task is a [multi task][] so any targets, files and options should be specified according to the [multi task][] documentation. [multi task]: https://github.com/gruntjs/grunt/wiki/Configuring-tasks

Options

language

Type: string Default: js

Specifies the script language and compiler to use alongside HAML.

Accepts following values: coffee, js, or ruby. If given coffee or js it will use haml-coffee or haml-js respectively. If given ruby it will shell out to the haml gem executable.

target

Type: string Default: html

Specifies the target language to compile to.

Accepts the following values: js or html. For js the template is generated and for html the template is both generated and rendered into its resultant HTML.

If language is set to ruby then target must be set to html.

placement

Type: string Default: global

Specifies where to place the resultant template.

Currently accepts either global or amd.

  • global places the template on the window.
  • amd uses AMD to load the template.

Defined only for target == 'js'.

namespace

Type: string Default: window.HAML

Specifies the global object to store the compiled HAML templates in.

Defined only for target == 'js' and placement == 'global'.

name

Type: string Default: basename without extension of the input HAML file

Specifies the name to store the compiled HAML template as in the object specified by namespace.

With a name of 'apple' and a namespace of this._template, you'd get something like this:

window.HAML['apple'] =  function(locals) {
    // template code
};

Defined only for target == 'js' and placement == 'global'.

context

Type: object Default: {}

Set variables that can be evaluated within haml templates.

The haml file:

%h1= "hello #{ @greet }"

With the configuration

context: {
  'greet': 'Morgan Freeman'
}

Would compile to

<h1>hello Morgan Freeman</h1>

Defined only for target == 'html'

dependencies

Type: object Default: {}

Specifies any module dependencies of the HAML file that must be loaded via the AMD define statement. These are automatically appended to if there are any require statements in the HAML code.

With the following HAML file:

!= require('path/to/other')()
%p Hello World

And the following options (in the Gruntfile.js):

haml: {
  compile: {
    files: // ...
    options: {
      dependencies: {
        $: 'jquery',
        _: 'underscore'
      }
    }
  }
}

The resultant template would be something like this:

define(['jquery', 'underscore', 'path/to/other'], function($, _, other) {
    // template code
});

Defined only for target == 'js'.

bare

Type: boolean Default: true

Compile the JavaScript without the top-level function safety wrapper.

Defined only for language == 'coffee' and target == 'js'.

precompile

Type: boolean Default: true

Process HAML templates to precompiled JavaScript or not. Defaults to true for target == 'js' and is forced to false for target == 'html'.

rubyHamlCommand

Type: string Default: haml -t ugly

The shell command which will be ran to compile the HAML. The path to the HAML file will be passed as the last command-line argument.

*Defined only for language == 'ruby'

includePath

Type: boolean Default: false

Specifies whether or not to include the relative path in automatic generated name.

When enabled, you'll get results like window.HAML['path/to/template'] instead of window.HAML['template'].

Defined only placement == 'global'.

pathRelativeTo

Type: string Default: ./

Specifies the path names will be based from.

If pathRelativeTo == ./templates/ you would get:

window.HAML['example']

Otherwise, with ./ you'll get:

window.HAML['templates/example']

Defined only placement == 'global'.

Usage examples

haml: {
  one: {
    files: {
      // 1:1 compile
      'path/to/result.js': 'path/to/source.haml',

      // compile and concat into single file
      'path/to/another.js': ['path/to/sources/*.haml', 'path/to/more/*.haml']
    }
  },

  // compile individually into dest, maintaining folder structure
  two: {
    files: grunt.file.expandMapping(['path/to/*.haml'], 'path/to/dest/', {
      rename: function(base, path) {
        return base + path.replace(/\.haml$/, '.js');
      }
    })
  }
}

Release History

  • 2013-10-09   v0.8.0   Update version of haml-coffee 1.13.x Rendering to HTML with partials now works correctly
  • 2013-08-21   v0.7.0   Replace execSync with proper use of exec.
  • 2013-08-11   v0.6.1   Update version of haml-coffee 1.11.x
  • 2013-08-06   v0.6.0   Add 'precompile', 'includePath', and 'pathRelativeTo' option @leahciMic
  • 2013-05-27   v0.5.0   Add 'ruby' as a language option Update version of haml-coffee 1.10.x
  • 2013-04-15   v0.4.0   Full support of grunt 0.4.x
  • 2013-03-21   v0.3.2   Corrected placement option to match readme.
  • 2013-01-27   v0.3.1   Update to current version of grunt.
  • 2012-12-19   v0.3.0   Name changed to grunt-haml Default target changed to html
  • 2012-12-18   v0.1.3   Updated README.
  • 2012-12-18   v0.1.2   Fixed package.json syntax error.
  • 2012-12-18   v0.1.1   Fixed package.json dependencies.
  • 2012-12-18   v0.1.0   Rewrite from scratch (referencing grunt-contrib). Support for full gamut of options.
  • 2012-12-16   v0.0.2   Fixed a syntax error in the package.json (missing comma).
  • 2012-11-06   v0.0.1   Initial release; only slightly modified from what grunt-contrib-coffee was at the time.

Task submitted by Ryan Leckey

This file was generated on Wed Jan 29 2014 11:31:48.

grunt-haml's People

Contributors

alockwood05 avatar joneshf avatar jroxendal avatar kerbyfc avatar leahcimic avatar mehcode avatar melcher 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

Watchers

 avatar  avatar  avatar  avatar

grunt-haml's Issues

Prevent escaping strings?

Currently passing:

%link{rel : "stylesheet", type : "text/css", href : "/<%= grunt.config.get('pkg.name') %>.css"}

Results in:

<link rel="stylesheet" type="text/css" href="/&lt;%= grunt.config.get('pkg.name') %&gt;.css" />

Is there a way to prevent escaping so the final output so the final result looks more like:

<link rel="stylesheet" type="text/css" href="/<%= grunt.config.get('pkg.name') %>.css" />

Currently to achieve this functionality I have switched the html_escape functionality inside haml.js to just return the text, though I'm sure this is going to break tests and is a short term solution.

Thanks.

+include partials error: window is not defined

According to this comment, grunt-haml is able to include partials (using haml-coffee by adding the language: 'coffee' option, with the default target target: 'html').

Somehow this throws the following error when executing the grunt task:
>> ReferenceError: window is not defined

Is it not possible to transpile the partial directly in the resulting main.html file?

# main.haml
%h1 Main content
+include 'partial'

# partial.haml
%h2 Partial content

# transpiles to main.html
<h1>Main content</h1>
<h2>Partial content</h2>

Dynamic File Mapping

Is there any way to not explicitly set the source/destination mapping for each haml file?

Support javascript backend through haml.js

Would need a compiler option flag (with values such as haml.js and haml-coffee). Also I'd like a separate options hash that is just forwarded directly to whatever compiler is selected.

Exception thrown when transpiling each src/dest group of files.

undefined is not a function thrown on line haml.js#L58, because file.src is undefined. I haven't found out why yet.

Gruntfile.js:

haml: {
  prod: {
    files: {
      expand: true,
      src: "src/haml/**/*.haml",
      ext: "html",
      rename: function(dest, src) {
        return dest + path.basename( src );
      }
    },
    options: {
      language: "ruby",
      target: "html"
    }
  }
}

Folder structure:

|_app
|_src
   |_haml
      | launchpage.haml      

Haml 4.0.6

Lines following a -# comment within a <script> tag disappear after upgrade to 0.6.1

HAML code:

  %body
    %script{type: 'text/javascript'}
      BB.preloadedData = {};
      -# do NOT change the following two lines as we're replacing them via a regex in the insert_json_into_dom grunt task
      BB.preloadedData.about = [];
      BB.preloadedData.projects = [];

relevant output with 0.6.1 and 0.8.0 (lacking "about" and "projects"):

    <script type='text/javascript'>BB.preloadedData = {};
    </script>

relevant output with 0.6.0:

<script type='text/javascript'>BB.preloadedData = {};
      BB.preloadedData.about = [];
      BB.preloadedData.projects = [];
</script>

The comment is NOT supposed to appear in the rendered HTML. Am I doing something wrong and is this intended behaviour inside <script> tags?

Haml to static html.

There is not a single tool to produce static html templates. I find them useful when I start a new project and divide my content into (kind of) reusable, self-supporting little css-html-js modules.
It's not really an issue but it would be great to have something that allows me to build more complicated modules and sites from those single modules I already have keeping the process DRY.
So here it is: add some easy way of nesting partials in .haml files. Like

.wrapper
=partial('path/to/partial.haml')
Lorem ipsum dolor sit amet

Placement: global doesn't seem to be the default anymore

using grunt-haml v0.3.1 with readme from "Mon Jan 28 2013 23:23:38."

Docu

Placement
Type: string Default: global

which gave me:
define(function() {

whereas when adding the placement option with placement: 'global' i got the desired:
(function() {
var _ref;

if ((_ref = window.HAML) == null) {
window.HAML = {};
}

window.HAML

Improve documentation - use with AMD

In the documentation of this Grunt task, maybe it could be clarified that AMD dependencies can be added in two ways:

  1. Including them in the Gruntfile, when they are used by all HAML templates
  2. Including them in the particular template, when they are specific

In addition, the current documentation suggests adding the following line to express a dependency: != require('path/to/other')() (option 2 above). This assumes that the value of the module is a function and that we want to call it. In general, though, the value of the module may be a simple object or even a function that we don't want to call. I would suggest to modify the documentation as follows: != require('path/to/other').

haml-coffee & Require.js & Node.js & Backbone

Firstly have opened this issue in haml-coffee just to get some ideas, also i have worked with a a similar stack on rails and everything works great, but i am unable to get the templates rendered on a node backbone app. This is what i have:

I use this to compile JST file on command line:

haml-coffee -i public/javascripts/backbone/templates/test.hamlc -b -n window.JST 

This is the JST file thats generated:

(function() {
  var _ref;

 if ((_ref = window.JST) == null) {
   window.JST = {};
 }

 window.JST['test'] = function(context) {
 return (function() {
 var $o;

 $o = [];
 $o.push("<h1>yayyyyyyaa</h1>");
 return $o.join("\n");
}).call(context);
};
}).call(this);

and i try to load it using:

define ['backbone', 'marionette', 'text!javascripts/backbone/templates/test.jst'],    
(Backbone, Marionette, template) ->

 class Test extends Backbone.Marionette.ItemView
    template: JST[template]

I get:

JST undefined

I realized of course i am abusing the text plugin, thats just text coming in, switched to without text plugin, and still does not work.

Then i tried a new haml compiler option

haml-coffee -i public/javascripts/backbone/templates/test.hamlc -b -n window.JST -p amd

This generated:

(function() {
define(['hamlcoffee'], function(hc) {
    return function(context) {
        var render;

        render = function() {
            var $c, $e, $o;

            $e = hc.escape;
            $c = hc.cleanValue;
            $o = [];
            $o.push("<h1>yayyyyyyaa");
            $o.push("  " + $e($c(this.a)));
            $o.push("</h1>");
            return $o.join("\n").replace(/\s(\w+)='�true'/mg, ' $1').replace(/\s(\w+)='�false'/mg, '');
        };
        return render.call(context);
       };
    });
   }).call(this);

This almost worked, but i get:

hc undefined

I added hamlcoffee to my require.js config, but that does not help.

What is the correct way to get haml-coffee templates working on this stack? I have looked over a lot and could not find any examples, what am i doing wrong?

Thanks!

context and slash

When passing text with slash (in my case it is a path to script file) by context option instead of / i get &#47;

Conditional comments support

I would like to use the conditional comments feature by using grunt-haml. But got some error.
This is my grunt task configuration:

{
    haml: {
        files: {
            expand: true,
            cwd: 'app',
            dest: '.tmp',
            src: '{,*/}*.haml',
            ext: '.html'
        }
    }
}

and this is my .haml code:

!!! 5
/[if IE]
  %html(class="no-js lt-ie9 lt-ie8 lt-ie7")

The error:

Running "haml:files" (haml) task
with(locals || {}) {
  try {
   var _$output="<!DOCTYPE html>\n"
"<!--adfdf\n\n%html(class="no-js lt-ie9 lt-ie8 lt-ie7")-->";
 return _$output;  } catch (e) {
    return "\n<pre class='error'>" + html_escape(e.stack) + "</pre>\n";
  }
}
>> SyntaxError: Unexpected identifier
Warning: Haml failed to compile. Use --force to continue.

Aborted due to warnings.

Make execSync optional or use something else (or fix execSync)

Here is the problem. I'm on a modern OS. python is python 3. execSync depends on node-gyp which requires python to be in the PATH and be python 2. node-gyp should really use python2 instead. Or we should use something else besides execSync. Something.. it's getting a bit annoying to install grunt-haml on my box.

Passing arguments to haml-js?

I'd like to pass arguments to haml-js to escape HTML by default. The documentation says I should do this:

Haml(src, {escapeHtmlByDefault: true})

How do I do this from grunt-haml?

Grunt 0.4 Release

I'm posting this issue to let you know that we will be publishing Grunt 0.4 on Monday, February 18th.

If your plugin is not already Grunt 0.4 compatible, would you please consider updating it? For an overview of what's changed, please see our migration guide.

If you'd like to develop against the final version of Grunt before Monday, please specify "grunt": "0.4.0rc8" as a devDependency in your project. After Monday's release, you'll be able to use "grunt": "~0.4.0" to actually publish your plugin. If you depend on any plugins from the grunt-contrib series, please see our list of release candidates for compatible versions. All of these will be updated to final status when Grunt 0.4 is published.

Also, in an effort to reduce duplication of effort and fragmentation in the developer community, could you review the grunt-contrib series of plugins to see if any of your functionality overlaps significantly with them? Grunt-contrib is community maintained with 40+ contributors—we'd love to discuss any additions you'd like to make.

Finally, we're working on a new task format that doesn't depend on Grunt: it's called node-task. Once this is complete, there will be one more conversion, and then we'll never ask you to upgrade your plugins to support our changes again. Until that happens, thanks for bearing with us!

If you have any questions about how to proceed, please respond here, or join us in #grunt on irc.freenode.net.

Thanks, we really appreciate your work!

Bad assignation of partials with includePath: true

Having gruntfile

    haml:
      compile:
        files:
          "assets/compiled/templates.js": [ "assets/javascripts/**/*.hamlc" ]
        options:
          target: 'js'
          language: 'coffee'
          includePath: true
          pathRelativeTo: './assets/javascripts/backbone/',
          dependencies:
            $: 'jquery',
            _: 'underscore'
            I18n: 'i18n'

and some partials in my views I end up with the error

Running "haml:compile" (haml) task
>> [stdin]:2:41: error: the variable "_basket_prize" can't be assigned with ?= because it has not been declared before
>> window.HAML.apps/lottery/show/templates/_basket_prize ?= {}
>>                                         ^^^^^^^^^^^^^
Warning: Haml failed to compile. Use --force to continue.

as you can see views are correctly assigned with

window.HAML['tasks'] = function(context) {
    return (function() {
...

but templates are wrongly assigned with

window.HAML.apps/lottery/_basket_prize['jst'] = function(context) {
    return (function() {
      var $o;
      $o = [];
      $o.push("<div class='name'></div>\n<div class='quantity'></div>\n<div class='remove'>&times;</div>");
      return $o.join("\n").replace(/\s(?:id|class)=(['"])(\1)/mg, "");
    }).call(context);
  };

Any idea how to solve this issue?

Limit number of haml processes run together

Currently this plugin issues command to run haml commands corresponding to all haml files at once. This causes my server to crash when I run grunt-haml while deploying.

At one point I noted that there were more than 60 simultaneous haml processes.

It would be good, if we could run these processes sequentially or cap the number of processes being run simultaneously.

PS: I am using haml gem, i.e. ruby haml.

Windows Paths shouldn't contain backslashes

When using the

includePath: true

option, the generated paths are not consistent across Windows/Unix systems. This makes it difficult for my team (which develops on both systems) to collaborate, and it seems like converting Windows paths to Unix paths is the more sensible option than the other way around.

Option to run haml with bundle exec

Is there any option to compile haml with bundle exec haml not just haml? In order not to require global haml installation and use one from Gemfile instead.

weird error

How to fix this error? please help me.

[email protected] install /Thainguyen/KGU-demo/node_modules/grunt-haml-leahcimic/node_modules/execSync/node_modules/ffi/node_modules/ref
node-gyp rebuild

gyp ERR! build error
gyp ERR! stack Error: not found: make
gyp ERR! stack at F (/usr/local/lib/node_modules/npm/node_modules/which/which.js:43:28)
gyp ERR! stack at E (/usr/local/lib/node_modules/npm/node_modules/which/which.js:46:29)
gyp ERR! stack at /usr/local/lib/node_modules/npm/node_modules/which/which.js:57:16
gyp ERR! stack at Object.oncomplete (fs.js:107:15)
gyp ERR! System Darwin 11.4.2
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Thainguyen/KGU-demo/node_modules/grunt-haml-leahcimic/node_modules/execSync/node_modules/ffi/node_modules/ref
gyp ERR! node -v v0.10.16
gyp ERR! node-gyp -v v0.10.9
gyp ERR! not ok
npm ERR! weird error 1
npm ERR! not ok code 0

Ping grunt-contrib and grunt-haml to see what to do next with it

I'd like to have it be an official grunt-contrib package. I'm not sure on the process for that so I thought I'd ping you two and see what happens. Thank you for your time.

//cc @ctalkington, @tkellen


I needed haml + coffee in grunt a while back so I started work on this. Then cleaned and dusted today. The package grunt-haml looks defunct. If it isn't @andrewrjones, is there some way we can consolidate what we have if you see anything you'd want to add, etc?

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.