Giter Site home page Giter Site logo

netzpirat / haml-coffee Goto Github PK

View Code? Open in Web Editor NEW
442.0 442.0 54.0 1.17 MB

Haml templates where you can write inline CoffeeScript.

Home Page: http://haml-coffee-online.herokuapp.com/

License: MIT License

CoffeeScript 71.17% Ruby 1.33% JavaScript 0.13% HTML 15.03% Haml 12.34%

haml-coffee's People

Contributors

bastjan avatar baumicon avatar cesine avatar dn avatar fred104 avatar gillnana avatar guncha avatar huetsch avatar janv avatar jewel avatar joneshf avatar kalasjocke avatar lfkellogg avatar lorensr avatar mehcode avatar miketoth avatar netzpirat avatar nguyenj avatar plietar avatar pwnall avatar rafalsobota avatar rharriso avatar russellmcc avatar scottbrady avatar sebastiandeutsch avatar sh-ft avatar tomykaira avatar troywarr avatar vendethiel 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  avatar  avatar  avatar  avatar  avatar

haml-coffee's Issues

surround, succeed, etc, should work and be documented

Ruby HAML has a number of filters (I think that's the word for them), like:

= succeed "," do
   %code
      some code

These don't seem to work for me, and they aren't mentioned in the docs. Can you mention their status in the README, and consider implementing them if possible?

succeed/surround etc. wrappers should run in the template's context

While using the wrappers, I was surprised that the properties of my context were not available at this, like everywhere else in the template. The this-context in the wrapper is window instead.

Was this an oversight or a conscious decision? If there are no reasons against it I would submit a pull request, but I'd like to hear if this is a good idea first.

(Additionally, setting a custom wrapper via Haml-Coffee-Assets' config.hamlcoffee.customSurround, did not seem to work, but that's a different issue)

lines ending in a comma do not continue

According to the HAML docs, this looks like valid syntax:

%article
  = HAML['title']({icon: "repeat",
                   title: "Setting your build up manually"})

The docs say: "A line of Ruby code can be stretched over multiple lines as long as each line but the last ends with a comma. For example:

- links = {:home => "/",
    :docs => "/docs",
    :about => "/about"}

But hamlcoffee (latest version) tells me "org.mozilla.javascript.JavaScriptException: Block level too deep in line 2 (haml-coffee.js#419)". (This is being used in dieter, the clojure asset pipeline, which uses Rhino).

I also tried it with a '-' instead of a '=', and got the same result.

unquoted attribute value evaluated as coffeescript and not as ruby

Accoding to the REAMDE

When you define an attribute value without putting it into quotes (single or double quotes), it's considered to be CoffeeScript code to be run at render time.

Consider this simple snippet:

%img(src="#{im_not_defined}")

I'd expect a ruby compilation error but instead I get a javascript error.

Quote escaping in interpolated string value attributes

Interpolated strings aren't escaped:

- str = "It's a wonderful life"
%a(title=str) One
%a(title="#{str}") Two

compiles to the following javascript:

str = "It's a wonderful life";
$o.push("<a title='" + ($e($c(str))) + "'>One</a>\n<a title='" + str + "'>Two</a>");

(The single quote in "str" causes this to generate invalid HTML.)

This is similar to #24.

ruby 1.9 hash syntax doesn't work, text on same line as a tag

Two issues I've come across. One is the old ruby hash syntax {:this => 'that'} that is being used in the regular expression that parses the tags attributes. I think the new syntax { this: 'that' } makes more sense since it matches the javascript notation.

The other thing I noticed that doesn't work is having content on the same line as a tag, for example: %h1 Hello

Get a simple function

Hello, and thanks for this great project !

I'm trying to get from hamlc a single function, and avoid it to assign directly, like jade's client option.
I thought this would work :

      when 'standalone'
        @precompile()

What do you think ?

OUTPUT argument produces "Bad file descriptor"

I can't seem to provide the OUTPUT parameter as a directory or file path, and I even tried touch'ing it to make it exist. Any tips?

~ haml-coffee app ./public/javascripts/app/views.js 
  [haml coffee] compiling directory app
    [haml coffee] compiling file testing.haml

fs.js:221
  return binding.open(path, stringToFlags(flags), mode);
                 ^
Error: EBADF, Bad file descriptor './public/javascripts/app/views.js'
    at Object.openSync (fs.js:221:18)
    at Object.writeFileSync (fs.js:483:15)
    at /usr/local/lib/node_modules/haml-coffee/lib/command.js:37:20
    at /usr/local/lib/node_modules/haml-coffee/node_modules/glob/lib/glob.js:52:5

Data attribute can’t be a string

It seems that data attributes can’t be simple strings, only HTML5 data-something attributes. But HTML has a data attribute at the object element. Did I forget something?

Template:

str = """
%object{ :type => "image/svg+xml", :data => "some.svg" }
%object(type="image/svg+xml" data="some.svg")
%object{ :data => "some.svg", :type => "image/svg+xml" }
%object(data="some.svg" type="image/svg+xml")
"""
console.log(require('haml-coffee').compile(str)())

Actual output:

<object type='image/svg+xml'></object>
<object type='image/svg+xml'></object>
<object data-type='image/svg+xml'></object>
<object data-type='image/svg+xml'></object>

Expected output (= Haml’s output):

<object data='some.svg' type='image/svg+xml'></object>
<object data='some.svg' type='image/svg+xml'></object>
<object data='some.svg' type='image/svg+xml'></object>
<object data='some.svg' type='image/svg+xml'></object>

Haml runtime and optimization

Here is a sample of the output of rendering a template.

    return function(context) {
      var render;
      render = function() {
        var $c, $e, $o, _ref;
        $e = function(text, escape) {
          return ("" + text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/\//g, '&#47;').replace(/"/g, '&quot;');
        };
        $c = function(text) {
          switch (text) {
            case null:
            case void 0:
              return '';
            case true:
            case false:
              return '�' + text;
            default:
              return text;
          }
        };

It's not too much boilerplate runtime but when you have a large project with several dozen files you start to look for duplicate code. It would reduce the size of our final built file by a good bit if we could factor out the HTML escape function, etc into a runtime file that is required and referenced.

On optimization, it would be nice if haml-coffee detected things like new lines in blocks and didn't render the newline. We don't need the HTML to be pretty-printed.

Some things to think about. I can jump in and help on this if you'd like.

problem with attr: 'false'

I've seen a couple bugs about this that say its fixed, but I can't get it working.

Haml behaves differently than hamlc in this case:

%param{ :value => 'false' }
%param{ :value => false }

In haml, this gets rendered to:

<param value='false' />
<param />

hamlc gets rendered to

<param />
<param />

There is no way that I can tell to set value to be 'false' other than to do this:

!= "<param value = 'true' />"

Attributes without values don't work together with linebreaks

This works:

%foo(bar baz)
<foo bar baz></foo>

This also works:

%foo(bar=""
     baz="")
<foo bar='' baz=''></foo>

This, however, doesn't:

%foo(bar
     baz="")
  #{ red }[haml coffee] CoffeeScript compilation error:#{ reset } SyntaxError: unexpected STRING
SyntaxError: unexpected STRING
  at Object.exports.throwSyntaxError (/Users/jan/development/haml-coffee/node_modules/coffee-script/lib/coffee-script/helpers.js:209:13)
  at Object.parser.yy.parseError (/Users/jan/development/haml-coffee/node_modules/coffee-script/lib/coffee-script/coffee-script.js:245:20)
  at Object.parse (/Users/jan/development/haml-coffee/node_modules/coffee-script/lib/coffee-script/parser.js:535:22)
  at Object.exports.compile.compile [as compile] (/Users/jan/development/haml-coffee/node_modules/coffee-script/lib/coffee-script/coffee-script.js:36:25)
  at Function.module.exports.CoffeeMaker.compile (/Users/jan/development/haml-coffee/src/cli/coffee-maker.coffee:96:31)
  at ReadStream.exports.run (/Users/jan/development/haml-coffee/src/cli/command.coffee:198:49)
  at ReadStream.EventEmitter.emit (events.js:93:17)
  at TTY.onread (net.js:417:51)

quote escaping in value attributes

Attribute values with single quotes break the template. e.g. name = "asdf ' asdf"

%input{ :value => @name }

Return this HTML.

<input asdf'="" value="asdf">

It should be
<input value="asdf ' asdf">

Markdown filter

Would you consider adding a :markdown filter that grabs all of its text content and calls like a markdown render function if its specified? I'm not asking to include the support by default as that would be an interesting amount of overhead (unless you want to of course); I can provide a haml.markdown function to the template.


This could be implemented by allowing custom filters to be able to be defined to just call some passed function, etc.

Doctype bang does nothing

For example:

!!! 5
%html{lang: 'en'}
  %head
    %title Hello

  %body
    %p Hello!

Gets turned into, including the leading blank line:

<html lang="en">
  <head>
    ...

Without the doctype declaration. I've resorted to just writing <!doctype html>, but it's just not the same :P

global leaks

Added support to consolidate.js, though mocha is reporting global leaks:

  haml-coffee
    ✓ should support locals (86ms)
    0) should support locals
    ✓ should not cache by default  
    ✓ should support caching  


  ✖ 1 of 30 tests failed:

  0) haml-coffee should support locals:
     Error: global leaks detected: __filename, __dirname, module, require, fn, $e, $c

Error when loading a partial

Hey,
I'm using haml-coffee together with spine.js
I tried to load a partial inside my haml file.

%h1 HEADER
= partial("partial")

I got the following Error: Uncaught ReferenceError: partial is not defined

When I look into my js code i can see the following:

$o.push("<h1>HEADER</h1>");
$o.push("" + $e($c(partial('partial'))));

So I think the partial call isn't resolved properly

Tag interpolation

Something like this : %#{container}
Only parse %#{.... %a#{bc} should (imho) not be valid.
I was thinking we could modify the Node.Haml matching to find %#{}.
Possible ? Interesting?

Globally accessible helpers - best approach to do this.

Hi,

I would like to ask you what is the best approach to create a globally accessible helper lib?

I mean I would like to create a few (ralis like) methods (look below), wich I could use in every template.
I am using haml-coffee with haml_coffee_assets.

- sum = (a, b) ->
  %div
    %span= a
    %span= b
    %span= a+b

Update development information

  1. First step should be npm install
  2. cake watch doesn't run because of the following missing dependencies: async, browserify. These should be added to package.json
  3. cake watch does not exist.

Thinking out loud with inheritance

Disclaimer: Thinking out loud here.


Any thoughts on allowing template inheritance? I know haml itself doesn't do it.
Haml is lacking directives which would make inheritance possible.

-# parent.haml
!!!
%html
  %body
    :block 'name'
-# child.haml
-# The directive prevents haml outside of :block sections as well 
-#    as defining the parent structure and blocks
..extends 'parent'  
:block 'name'
  %p Hello World

If we render child.haml we should get:

<!DOCTYPE html>
<html>
  <body>
    <p>Hello World</p>
  </body>
</html>

Mixed attribute notation is broken

This is obviously not a critical bug, but I noticed the other day when I was porting some Ruby haml files over to haml-coffee that mixed attribute notation of the following form is broken:

%video{:id => "foo", name: "bar"}

Whereas either of the following works:

%video{:id => "foo", :name => "bar"}
%video{id: "foo", name: "bar"}

Compile error for simple haml

I tested it with simple haml:

%html
%body
%h1
This is a test file for learning HAML!

And here is what I got:

antonkulaga@antonkulaga-home ~/denigma/semanticchat/public/semantictasks $ haml-coffee -i test.haml
[Haml Coffee] Compiling file test.haml to test.jst
#{ red }[haml coffee] CoffeeScript compilation error:#{ reset } TypeError: Object function () {
switch (this.options.placement) {
case 'amd':
return this.renderAmd();
case 'standalone':
return this.renderStandalone();
default:
return this.renderGlobal();
}
} has no method 'charCodeAt'
TypeError: Object function () {
switch (this.options.placement) {
case 'amd':
return this.renderAmd();
case 'standalone':
return this.renderStandalone();
default:
return this.renderGlobal();
}
} has no method 'charCodeAt'
at Lexer.exports.Lexer.Lexer.clean (/usr/local/lib/node_modules/haml-coffee/node_modules/coffee-script/lib/coffee-script/lexer.js:47:16)
at Lexer.exports.Lexer.Lexer.tokenize (/usr/local/lib/node_modules/haml-coffee/node_modules/coffee-script/lib/coffee-script/lexer.js:28:19)
at Object.exports.compile.compile (/usr/local/lib/node_modules/haml-coffee/node_modules/coffee-script/lib/coffee-script/coffee-script.js:54:39)
at Function.module.exports.CoffeeMaker.compileFile (/usr/local/lib/node_modules/haml-coffee/src/cli/coffee-maker.coffee:56:31)
at exports.run.source (/usr/local/lib/node_modules/haml-coffee/src/cli/command.coffee:141:58)
at Object.oncomplete (fs.js:297:15)

Pre-populating textarea adds extra newline characters

Assuming that @model.get("message") is a string with newline characters \n\r in it

%textarea.msgpost{:id => "post_#{@model.id}", :name => 'message', :placeholder => 'Add a comment, image or pdf...', :maxlength => '2000' }= @model.get("message")

returns a textarea with double the number of newline characters originally in the string.

However

%textarea.msgpost{:id => "post_#{@model.id}", :name => 'message', :placeholder => 'Add a comment, image or pdf...', :maxlength => '2000' }
    = @model.get("message")

does not insert extra newline characters.

Any ideas.

Layout ignored in Express.js 3

I am using Express.js 3.0.1 & HAML-Coffee 1.7.0.

The "layout.hamlc" is directly in "views" folder, but it is ignored, when I am rendering a template.

Adding "express-partials" package to my application did not help.

Conditional HTML attributes

I'm having some trouble generating option tags with the selected attribute set, currently I have this:

- for title in ['Mr', 'Mrs', 'Ms', 'Miss']
  %option{value: title selected: @title == title}= title

However the markup that it produces is this:

<option value="Mr" selected="Mr">Mr</option>
<option value="Mrs" selected="Mr">Mrs</option>
<option value="Ms" selected="Mr">Ms</option>
<option value="Miss" selected="Mr">Miss</option>

@title is 'Mr' for the above example.

Am I doing this wrong, is there a better approach to achieve the same thing?

Currently I am using haml-coffee-assets gem version 0.6.1, as this is the latest version I assume it is using the latest haml-coffee.

Passing an Object to Attributes

I want to be able to say something similar to:

- attributes = {something="something", class="myCssClass myOtherClass"}
- attributes.disabled = true if @disabled
%button[attributes]
  .icon
  = @text

This allows programmatically generating attributes.

The main use case is for attributes like disabled where setting to false or undefined will still generate an attribute where we would prefer not to.

Using an if statement is problematic as it duplicates many irrelevant attributes to construct the tag in each branch. This is even more troublesome when tag has content within it.

If there is a better way to accomplish this let me know. I'd be happy to work on a pull request if you can steer me where to start.

In Ruby Haml Attribute Methods are one way to accomplish this, but it seems more convoluted than necessary.

This is similar to #47 but seems more powerful and general.

%input{disabled: @disabled} always is disabled

Hi! Is it possible to evaluate values in tag attributes hash as in Ruby and not to create attributes which evaluate to false?
%input{disabled: @disabled} seems not to be possible in current implementation.

Inline evaluation output

There is key a difference between - foo -> and = foo -> code evaluation in what we get at compilation. The second syntax will not only output our result but either will try to create inner buffer to pass result into foo(). However this doesn't seem to work right for inline evaluations

= foo ->
  %br
  = bar()

will compile into

$o.push("" + $e($c(foo(function() {
  var $b;
  $b = [];
  $b.push("<br>");
  $o.push("" + $e($c(bar())));
  return $b.join("\n");
}))));

And therefore we will only get <br /> as incoming parameter to foo. The result of inline evaluation will be passed directly to main buffer. What we should expect as compilation result is

$o.push("" + $e($c(foo(function() {
  var $b;
  $b = [];
  $b.push("<br>");
  $b.push("" + $e($c(bar())));    // this line corrected
  return $b.join("\n");
}))));

Update project build process

Create Grunt tasks for:

  • Continuous test runner
  • Generate browser package
  • Tag version (also update in haml-coffee.coffee)
  • Publish to NPM
  • CoffeeLint

When all finished

  • Drop Guard/Ruby dependencies
  • Drop Cakefile

&apos; doesn't work in IE8

Hi,

I just discovered that & apos; doesn't work in IE8 and the solution is to use & #39; according to this bug [1]. I tracked down where the replacement happen in the code, but I didn't find any tests to verify this behavior, so I created this issue instead.

Do you think it's a good idea to change the replacement from & apos; to & #39;?

Thanks for a great library.

[1] https://bugzilla.mozilla.org/show_bug.cgi?id=661815

Double quotes for attributes?

Original Haml allows to set attr_wrapper option, which sets a quote char for element attributes. As i see, Haml-coffee renders html with single quotes, and there is no way to set to use double quotes. It would be nice to implement same attr_wrapper option.

Extraneous whitespace inserted into <textarea>

The original HAML implementation solves this problem, but it doesn't appear to be implemented yet in haml-coffee.

I'm assuming this happens with other whitespace-sensitive tags as well (e.g., pre ), but I haven't tried it.

There should at least be some way to replace whitespace within these tags with their corresponding HTML entities. Auto-detection of tags needing escaping would be nice.

I'm not aware of any workarounds other than clearing out the textarea with JavaScript.

An error on normal tags

This tag leads to an error in hamlcoffee. I dont see the actual error in my stack trace though, so I cant be more help. Hopefully this will reproduce for you. I think changing the word "data" fixes it, if that makes any sense.

%tbody.build-row{data-bind: "foreach: { data: xs}"}  

Add helper methods to help facilitate dynamic attributes on elements

This is a bit long, but requires some explanation…

I realize this may not be entirely Haml Coffee's responsibility, but since it already has a fair deal of code to help with generating tags, I figured it might be worth a request.

I'm quite fond of using the "partials" pattern to codify markup for a certain input element so it can be reliably repeated any time I need a special widget, fancy validation, etc. Basically what I'm talking about doing is writing a pared-down client-side SimpleForm.

So I've got a little form class that wraps a model and allows me to generate inputs with that model's attribute values populated (this also handles error responses, etc.). It's got hamlc partials for each possible type, so I may write something like:

.form-inputs
  %fieldset
    %legend Major Details
    %fieldset
      != @form.input('name')
      != @form.input('description')
      != @form.input('price', as: 'float', attrs: { min: 0.01, step: 0.01 })
      != @form.input('wins',  as: 'integer', attrs: { min: 0, step: 1 })
  %fieldset
    %legend Extra Info
    %fieldset
      != @form.input('retired',  as: 'boolean')
      != @form.input('status',   as: 'select', options: ['active', 'injured', 'resting', 'vacation', 'free'])
      != @form.input('birthday', as: 'date', attrs: { max: '2013-02-28' })
.form-actions
  %button(type='button' name='action' value='Cancel') Cancel
  %input(type='submit' value='Save')

And each call to @form.input is responsible for rendering a particular hamlc partial. For instance, integer.hamlc looks like this:

.input.integer
  %label.integer(for=@id)= @label
  %input.integer(id=@id name=@name type='number' value=@value step='1')
  %span.hint
  %span.errors

But what if the user wants to specify extra classes to go on the input field? What if they want to specify a min or a max? Or readonly or formnovalidate or disabled? Or random data-* keys?

Since (as far as I know), hamlc will only let me specify dynamic values for the values and not the keys of my attributes hash, this isn't possible without me writing my own code to generate arbitrary HTML tags. Which isn't my core competency.

Rails has the tag and content_tag methods to help in its Haml views. Can something similar be added to haml-coffee to allow views to safely generate arbitrary HTML tags and attributes?

Compiling a dir results in bad template names

I'm passing a directory to haml-coffee, as in

$ haml-coffee -i . -o ../../javascripts/templates.js -n window.JST

Where . is a directory containing the templates I want compiled to a script. Apparently haml-coffee is ignoring the file names and exporting every script as window['test'].

See screenshot below.

Screen Shot 2013-03-24 at 11 18 03 AM

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.