Code Monkey home page Code Monkey logo

slm's Introduction

Slm

Slm is a template language for js. Port of Slim but slimmer :)

Build Status Test Coverage Dependency Status devDependency Status NPM version Code Climate Gitter

A little bit of history

HAML -> Jade -> Slim -> Slm

Short list of the features

  • Elegant syntax
    • Short syntax without closing tags (Using indentation instead)
    • HTML style mode with closing tags
    • Shortcut tags (based on css selectors)
  • Safety
    • Automatic HTML escaping by default
    • Support htmlSafe attribute on String objects
  • Highly configurable and extendable via plugins
  • High performance
  • Easy integration with hapijs
  • Embedded engines like CoffeeScript, Markdown and Textile (TBD)

Links

How to start?

Install Slm with npm:

npm install slm --save

Configure to work with ExpressJS

// in app.js

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'slm');

Configure to work with hapijs

var Hapi = require('hapi');

var server = new Hapi.Server(3000);
server.views({
   engines: {
      'slm': require('slm')
   },
   basePath: __dirname + '/views',
   compileOptions: {
      basePath: __dirname + '/views',
      useCache: false // disable internal cache - useful for development
   },
   isCached: false // disable hapi view cache
});

server.route({
    method: 'GET', path: '/',
    handler: function (request, reply) {
      reply.view('index', {hello: "word"});
    }
});

server.start(function () {
  console.log('Server running at:', server.info.uri);
});

Syntax example

Here's a quick example to demonstrate what a Slm template looks like:

doctype html
html
  head
    title Slm Examples
    meta name="keywords" content="template language"
    meta name="author" content=this.author
    javascript:
      alert('Slm supports embedded javascript!')

  body
    h1 Markup examples

    #content
      p This example shows you how a basic Slm file looks.

    == content()

    - if this.items.length
      table#items
        - for item of this.items
          tr
            td.name = item.name
            td.price = item.price
    - else
      p No items found Please add some inventory.
        Thank you!

    div id="footer"
      == partial('footer')
      | Copyright © ${this.year} ${this.author}

Indentation matters, but the indentation depth can be chosen as you like. If you want to first indent 2 spaces, then 5 spaces, it's your choice. To nest markup you only need to indent by one space, the rest is gravy.

Line indicators

Text |

The pipe tells Slm to just copy the line. It essentially escapes any processing. Each following line that is indented greater than the pipe is copied over.

body
  p
    |
      This is a test of the text block.

The parsed result of the above:

<body><p>This is a test of the text block.</p></body>

The left margin is set at the indent of the pipe + one space. Any additional spaces will be copied over.

body
  p
    | This line is on the left margin.
       This line will have one space in front of it.
         This line will have two spaces in front of it.
           And so on...

You can also embed html in the text line

- for (var a in this.articles)
  | <tr><td>${a.name}</td><td>${a.description}</td></tr>

Text with trailing white space .

The single dot tells Slm to copy the line (similar to |), but makes sure that a single trailing white space is appended.

Inline html < (HTML style)

You can write html tags directly in Slm which allows you to write your templates in a more html like style with closing tags or mix html and Slm style.

<html>
  head
    title Example
  <body>
    - if this.articles.length
      table
        - for (var a of this.articles)
          <tr><td>${a.name}</td><td>${a.description}</td></tr>
  </body>
</html>

Control code -

The dash denotes control code. Examples of control code are loops and conditionals. Blocks are defined only by indentation. If your js code needs to use multiple lines, append a backslash \ at the end of the lines. If your line ends with comma , (e.g because of a method call) you don't need the additional backslash before the linebreak. Slm inserts ( and ) for if, for, else if automatically. So you JS code is more readable.

body
  - if !this.articles.length
    | No inventory

Output =

The equal sign tells Slm it's a JS call that produces output to add to the buffer. If your JS code needs to use multiple lines, append a backslash \ at the end of the lines, for example:

= javascript_include_tag(\
   "jquery",
   "application")

If your line ends with comma , (e.g because of a method call) you don't need the additional backslash before the linebreak. For trailing or leading whitespace the modifiers > and < are supported.

  • Output with trailing white space =>. Same as the single equal sign (=), except that it adds a trailing white space. The legacy syntax =' is also supported.
  • Output with leading white space =<. Same as the single equal sign (=), except that it adds a leading white space.

If you use Slm as express view engine, you have to make the function available to the view render, eg:

res.render('viewname', { items: some.result.data, foofunc: foofunc })

Then in your slm file you can call foofunc:

p = this.foofunc()

Output without HTML escaping ==

Same as the single equal sign (=), but does not go through the escapeHtml method. For trailing or leading whitespace the modifiers > and < are supported.

  • Output without HTML escaping and trailing white space ==>. Same as the double equal sign (==), except that it adds a trailing white space.
  • Output without HTML escaping and leading white space ==<. Same as the double equal sign (==), except that it adds a leading white space.

Output in Javascript j

To output data from the node side within Javascript there is a j function:

javascript:
  var user = ${=j(this.user)};

Code comment /

Use the forward slash for code comments - anything after it won't get displayed in the final render. Use / for code comments and /! for html comments

body
  p
    / This line won't get displayed.
      Neither does this line.
    /! This will get displayed as html comments.

The parsed result of the above:

<body><p><!--This will get displayed as html comments.--></p></body>

HTML comment /!

Use the forward slash immediately followed by an exclamation mark for html comments (<!-- ... -->).

IE conditional comment /[...]

/[if IE]
    p Get a better browser.

renders as

<!--[if IE]><p>Get a better browser.</p><![endif]-->

HTML tags

Doctype tag

The doctype tag is a special tag which can be used to generate the complex doctypes in a very simple way.

XML VERSION

doctype xml
  <?xml version="1.0" encoding="utf-8" ?>

doctype xml ISO-8859-1
  <?xml version="1.0" encoding="iso-8859-1" ?>

XHTML DOCTYPES

doctype html
  <!DOCTYPE html>

doctype 5
  <!DOCTYPE html>

doctype 1.1
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

doctype strict
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

doctype frameset
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

doctype basic
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"
    "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">

doctype transitional
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

HTML 4 DOCTYPES

doctype strict
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">

doctype frameset
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
    "http://www.w3.org/TR/html4/frameset.dtd">

doctype transitional
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

Closed tags (trailing /)

You can close tags explicitly by appending a trailing /.

img src="image.png"/

Note, that this is usually not necessary since the standard html tags (img, br, ...) are closed automatically.

Trailing and leading whitespace (<, >)

You can force Slm to add a trailing whitespace after a tag by adding a >.

a> href='url1' Link1
a> href='url2' Link2

You can add a leading whitespace by adding <.

a< href='url1' Link1
a< href='url2' Link2

You can also combine both.

a<> href='url1' Link1

Inline tags

Sometimes you may want to be a little more compact and inline the tags.

ul
  li.first: a href="/a" A link
  li: a href="/b" B link

For readability, don't forget you can wrap the attributes.

ul
  li.first: a[href="/a"] A link
  li: a[href="/b"] B link

Text content

Either start on the same line as the tag

body
  h1 id="headline" Welcome to my site.

Or nest it. You must use a pipe or an apostrophe to escape processing

body
  h1 id="headline"
    | Welcome to my site.

Dynamic content (= and ==)

Can make the call on the same line

body
  h1 id="headline" = this.pageHeadline

Or nest it.

body
  h1 id="headline"
    = this.pageHeadline

Attributes

You write attributes directly after the tag. For normal text attributes you must use double " or single quotes ' (Quoted attributes).

a href="http://slm-lang.com" title='Slm Homepage' Goto the Slm homepage

You can use text interpolation in the quoted attributes.

Attributes wrapper

If a delimiter makes the syntax more readable for you, you can use the characters (...), [...] to wrap the attributes. You can configure these symbols.

body
  h1(id="logo") = this.pageLogo
  h2[id="tagline" class="small tagline"] = this.pageTagline

If you wrap the attributes, you can spread them across multiple lines:

h2[id="tagline"
   class="small tagline"] = this.pageTagline

You may use spaces around the wrappers and assignments:

h1 id = "logo" = page_logo
h2 [ id = "tagline" ] = this.pageTagline

Quoted attributes

Example:

a href="http://slm-lang.com" title='Slm Homepage' Goto the slm homepage

You can use text interpolation in the quoted attributes:

a href="http://${url}" Goto the ${url}

The attribute value will be escaped by default. Use == if you want to disable escaping in the attribute.

    a href=="&amp;"

You can break quoted attributes with backslash \

a data-title="help" data-content="extremely long help text that goes on\
  and one and one and then starts over...."

Javascript attributes

Write the javascript code directly after the =. If the code contains spaces you have to wrap the code into parentheses (...). You can also directly write hashes {...} and arrays [...].

body
  table
    - for var user of this.users
      td id="user-${user.id}" class=user.role
        a href=userAction(user, 'edit') Edit ${user.name}
        a href=pathToUser(user) = user.name

The attribute value will be escaped by default. Use == if you want to disable escaping in the attribute.

a href==actionPath('start')

You can also break javascript attributes with backslash \ or trailing , as describe for control sections.

Boolean attributes

The attribute values true, false, null and undefinded are interpreted as booleans. If you use the attribute wrapper you can omit the attribute assigment.

input type="text" disabled="disabled"
input type="text" disabled=true
input(type="text" disabled)

input type="text"
input type="text" disabled=false
input type="text" disabled=null

Attribute merging

a.menu class="highlight" href="http://slm-lang.com/" Slm-lang.com

This renders as

<a class="menu highlight" href="http://slm-lang.com/">Slm-lang.com</a>

You can also use an Array as attribute value and the array elements will be merged using the delimiter.

a class=['menu','highlight']
a class='menu','highlight'

Text interpolation

Use ES6 interpolation. The text will be html escaped by default.

body
  h1 Welcome ${current_user.name} to the show.
  | Unescaped ${=content} is also possible.

To escape the interpolation (i.e. render as is)

body
  h1 Welcome \${current_user.name} to the show.

Mixins

Mixins allow you to create reusable blocks of Slm.

= mixin('paragraph')
  p Hello from mixin!

.say
  = mixin('paragraph')

They are compiled to functions and can take arguments:

= mixin('paragraph', 'name')
  p Hello from ${this.name}!

.say
  = mixin('paragraph', 'me')

Even with default values:

= mixin('paragraph', 'name = me')
  p Hello from ${this.name}!

.say
  = mixin('paragraph')

And from partial:

// mixins.slm
= mixin('paragraph', 'name = me')
  p Hello from ${this.name}!

// index.slm
= partial('mixins')
.say
  = mixin('paragraph')

License

Slm is released under the MIT license.

Special Thanks

slm's People

Contributors

chrisnicola avatar dmitrytsepelev avatar faceyspacey avatar gitter-badger avatar mrmlnc avatar panman avatar realjoshbyrnes avatar robloach avatar simnalamburt avatar voondo 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  avatar

slm's Issues

Angular one time binding doesn't work

When you try to use Angular one time binding using ::, slm throws an error saying Unexpected token :. Should this be supported, since Slim supports this?

Documentation for `content()`, `partial()`, and `extend()`

Is there some documentation for content(), partial(), and extend()? I see the code in lib/vm.js, but I can't quite piece together everything that these functions can do.

In lieu of slm-specific documentation, is slm's version of these functions modelled after another template library? I don't see these functions, at least not in whole, in either haml, jade, or slim.

Mixins

Hello, @yury,

I'm very upset because of Pug performance (after 4 years with Jade) and interested in the development of Slm.

Typical example

code_2016-11-10_11-14-25

conemu64_2016-11-10_11-13-05

But I don't see support for Mixins.

I'll try to send PR, so let this issue be a reminder. How do you see the syntax of Mixins in your project?

Project is currently unlicensed

First, this package has literally saved my sanity. Parsing Slm and Slim templates is now so much faster in our project thanks to this library. So a HUGE thank you for making this available and working on it.

Do you have any license plans for this project?

Tag Interpolation

Can we use "tag interpolation"?

e.g. span.t1 click #[a(href="go/here") this] link should produce <span class="t1">click <a href="go/here">this</a> link</span>.

Maybe I'm just not finding this in the readme? I haven't searched in code yet.

How to output object data in script?

I have tried many variations to get an object from the Node side to the Slim side of things.
But the template doesn't (server-side) execute code within script tags.
Basically, what I want to end up with:

<script>
var scores={this is my object from the node side of things}
</script>

If I do e.g.

span = JSON.stringify(this.scores)

it works and prints the object

However, no version of

script var scores = JSON.stringify(this.scores)

works, as (I think) as soon as its within a script, slim assumes this is client side, and doesn't execute the code server side? Right?
How do I work around this?

Убрать кавычки

Фрагмент взят с Syntax example:

meta name="keywords" content="template language"

Чтобы еще сократить (сделать еще более Slim'ее) нужно убрать двойные кавычки.
Тогда будет выглядеть так:
meta name=keywords content=template\ language
Разделителем будет пробел.

meta name=author content=this.author
И сделать проверку на this (будет зарез. слово)

Лучше просто добавить такую возможность и оставить кавычки для поддержки пред. кода. Но Вам лучше знать, я просто предлагаю.

undefined in == content()

Hello @yury! I trying to use slm like pug and have trouble.

What I do wrong? What is correct way to use == content() to present layout extended partial?

Boolean Attributes

Currently, if attribute=false it's swallowed up (as expected) but attribute=true returns attribute="".

Wouldn't it make more sense that if attribute=true that it just returns attribute

I notice that there's an Issue (or 10) over on Siml (started by @yury). There were some talks about incompatibility with XHTML, but an XHTML dev would surely use attribute="" etc.

I'm started with doctype 5 but this doesn't seem to make a difference.
Is this intended behaviour? is there reasoning behind it?

new Template with options set causes error

template.js does not add mergeAttrs if options is set. I believe that it should add mergeAttrs if options.mergeAttrs is not set.

I have made a slight change, and will issue a pull request.

For reference, here is a Stack Trace:

TypeError: Cannot read property 'id' of undefined
  at Dispatcher.p._merge (/Users/jd/Desktop/Projects/slm/lib/filters/attr_merge.js:35:59)
  at Dispatcher.p.on_html_attrs (/Users/jd/Desktop/Projects/slm/lib/filters/attr_merge.js:28:15)
  at Dispatcher.eval [as _dispatcher] (<anonymous>:7:13)
  at DispatcherProto.compile (/Users/jd/Desktop/Projects/slm/lib/dispatcher.js:40:15)
  at Dispatcher.p.on_html_tag (/Users/jd/Desktop/Projects/slm/lib/html/html.js:22:43)
  at Dispatcher.eval [as _dispatcher] (<anonymous>:15:13)
  at DispatcherProto.compile (/Users/jd/Desktop/Projects/slm/lib/dispatcher.js:40:15)
  at Dispatcher.p._compileEach (/Users/jd/Desktop/Projects/slm/lib/filter.js:33:20)
  at Dispatcher.p.on_multi (/Users/jd/Desktop/Projects/slm/lib/filter.js:45:15)
  at Dispatcher.eval [as _dispatcher] (<anonymous>:29:13)
  at DispatcherProto.compile (/Users/jd/Desktop/Projects/slm/lib/dispatcher.js:40:15)
  at Dispatcher.p.on_html_tag (/Users/jd/Desktop/Projects/slm/lib/html/html.js:24:19)
  at Dispatcher.eval [as _dispatcher] (<anonymous>:15:13)
  at DispatcherProto.compile (/Users/jd/Desktop/Projects/slm/lib/dispatcher.js:40:15)
  at Dispatcher.p._compileEach (/Users/jd/Desktop/Projects/slm/lib/filter.js:33:20)
  at Dispatcher.p.on_multi (/Users/jd/Desktop/Projects/slm/lib/filter.js:45:15)
  at Dispatcher.eval [as _dispatcher] (<anonymous>:29:13)
  at DispatcherProto.compile (/Users/jd/Desktop/Projects/slm/lib/dispatcher.js:40:15)
  at Dispatcher.p.on_html_tag (/Users/jd/Desktop/Projects/slm/lib/html/html.js:24:19)
  at Dispatcher.eval [as _dispatcher] (<anonymous>:15:13)
  at DispatcherProto.compile (/Users/jd/Desktop/Projects/slm/lib/dispatcher.js:40:15)
  at Dispatcher.p._compileEach (/Users/jd/Desktop/Projects/slm/lib/filter.js:33:20)
  at Dispatcher.p.on_multi (/Users/jd/Desktop/Projects/slm/lib/filter.js:45:15)
  at Dispatcher.eval [as _dispatcher] (<anonymous>:29:13)
  at DispatcherProto.compile (/Users/jd/Desktop/Projects/slm/lib/dispatcher.js:40:15)
  at DispatcherProto.exec (/Users/jd/Desktop/Projects/slm/lib/dispatcher.js:36:15)
  at Engine.p.exec (/Users/jd/Desktop/Projects/slm/lib/engine.js:14:26)
  at Template.p.src (/Users/jd/Desktop/Projects/slm/lib/template.js:108:18)
  at Template.p.exec (/Users/jd/Desktop/Projects/slm/lib/template.js:100:31)
  at Template.p.compile (/Users/jd/Desktop/Projects/slm/lib/template.js:77:17)
  at /Users/jd/Desktop/Projects/slm/lib/slm.js:33:18
  at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)

single quotes are producing `Error: Unknown line indicator` errors

For example:

.content
  p
    ' foo bar

Here's the trace:

WARNING in ./app/assets/angular/policy/trading_policy/en.tmpl.html.slim
Module build failed: Error: Unknown line indicator
  /Users/jamesgillmore/codementor/remitano/p2p-frontend/app/assets/angular/policy/trading_policy/en.tmpl.html.slim, Line 4, Column 5
      ' foo bar
      ^

    at Parser.p._syntaxError (/Users/jamesgillmore/codementor/remitano/p2p-frontend/node_modules/slm/lib/parser.js:691:9)
    at Parser.p._parseLineIndicators (/Users/jamesgillmore/codementor/remitano/p2p-frontend/node_modules/slm/lib/parser.js:338:10)
    at Parser.p._parseLine (/Users/jamesgillmore/codementor/remitano/p2p-frontend/node_modules/slm/lib/parser.js:189:8)
    at Parser.p.exec (/Users/jamesgillmore/codementor/remitano/p2p-frontend/node_modules/slm/lib/parser.js:125:10)
    at Engine.p.exec (/Users/jamesgillmore/codementor/remitano/p2p-frontend/node_modules/slm/lib/engine.js:14:26)
    at Template.p.src (/Users/jamesgillmore/codementor/remitano/p2p-frontend/node_modules/slm/lib/template.js:107:18)
    at Template.p.exec (/Users/jamesgillmore/codementor/remitano/p2p-frontend/node_modules/slm/lib/template.js:99:31)
    at Template.p.compile (/Users/jamesgillmore/codementor/remitano/p2p-frontend/node_modules/slm/lib/template.js:76:17)
    at Object.module.exports (/Users/jamesgillmore/codementor/remitano/p2p-frontend/node_modules/slm-loader/index.js:16:22)
 @ ./app/assets/angular \.slim$
 @ ./app/assets/packs/application.js
 @ multi (webpack)-dev-server/client?http://localhost:3035 webpack/hot/dev-server ./app/assets/packs/application.js

Here's an example of the error in running in the browser on runkit:
https://runkit.com/faceyspacey/5abf6c4bb484d300124b5bfb

Getting an error thrown from a $ in the template

I'm trying to parse some of what were originally SLIM templates using webpack. I've created a pretty basic loader (code below) and it works for the most part but I'm getting some unusual errors being thrown. I'm also not getting line numbers from the errors, nor does the error look like something from the SLM library.

The Loader:

'use strict';

var loaderUtils = require("loader-utils");
var slm = require("slm");
var markdown = require("slm-markdown")
markdown.register(slm.template)

module.exports = function(source) {
  this.cacheable && this.cacheable(true);
  var query = loaderUtils.parseQuery(this.query);
  var req = loaderUtils.getRemainingRequest(this).replace(/^!/, "");
  slm.compile(source)()
}

The error

15:05:29 webpack.1 | Module build failed: SyntaxError: Unexpected token :
15:05:29 webpack.1 |   at VM.exports.runInThisContext [as runInContext] (vm.js:53:16)
15:05:29 webpack.1 |   at Template.p.exec (/Users/chrisnicola/src/wealthbar/node_modules/slm/lib/template.js:100:13)
15:05:29 webpack.1 |   at Template.p.compile (/Users/chrisnicola/src/wealthbar/node_modules/slm/lib/template.js:77:17)
15:05:29 webpack.1 |   at Object.module.exports (/Users/chrisnicola/src/wealthbar/webpack/loaders/slm.js:12:22)
15:05:29 webpack.1 |  @ ./webpack/wealthbar/views/index.coffee 43:23-63

The line that is causing it:

          p()
            | Net income ${{options.income - results.totalTax | number:2}}

If I remove the $ it works. This is an angular template so it is meant to return a currency value, hence the dollar sign.

Текст внутри тега

Как сделать?
<p>Lorem ipsum<span>text</span></p>
Можно так и написать. Но можно ли это сделать в стиле slm??

Render 'for' doesn't work

I've added the test for for:

lab.test('render with for', function(done) {
    assertHtml(template, [
      'ul',
      '  - for item in this.items',
      '    li = item.item',
      ],
      '<ul><li>test1</li><li>test2</li></ul>',
      {items:[{item:'test1'},{item:'test2'}]}, done);
  });

and see this:
expected '<ul><li></li><li></li><li></li></ul>' to deeply equal '<ul><li>test1</li><li>test2</li></ul>'

Partials, caching?

Hi team. I've been trying out slm with gulp-slm and some live reload tools. I'm seeing a problem where editing partials does not recompile with the updated HTML. I've put together a test project here - https://github.com/bradgreens/github-test-gulp-slm-partials.

When I make edits to https://github.com/bradgreens/github-test-gulp-slm-partials/blob/master/slm/partials/_header.slm, they appear on the first page load using the gulp stack.

When I make additional edits, I can see the entire gulp-watch system kick off and the gulp-slim code execute (via console logs), and gulp-livereload reload the browser. But after all of this the new partial HTML does not render out. If I restart gulp and re-save the main template test.slm I can get the changes to work.

It seems to me that the partial .slm code is getting cached or isn't seeing my changes after the first rendering.

When I make changes to the parent template, test.slm the changes do work with the full stack and I see the updates live in the browser, the problem seems specific to the included partial templates. Thanks in advance for any help.

orign html error!

slm:

<script>
 var a=b;
</script>

will be html:

<script><script>

my code dispeared!
I think any in orign tag pairs should be keep.

Баг: проблема с циклом for

- var names = ['Mike', 'Jack']
- for name in names
li
  a = name

выводит 0,1 вместо Mike и Jack
пробовал разными способами. Результат всегда 0,1,2 и т.д.

Хотя этот код работает нормально:

- var classes = ['table', 'colored']
      li class=classes

Reports error in parent template instead of partial

I am using partials in my template.

The error I was getting says: dashboard_3/slm/index.slm, Line 35, Column 13

It reports an error on such and such line of the parent template file name.
It should say the partial's file name instead because the error was in the partial on that line and column.
Ex. dashboard_3/slm/partials/nav.slm, Line 35, Column 13

Mixins синтаксис

Вопрос к Denis Malinochkin (@mrmlnc).
Не могли бы вы сделать синтаксис как в pugJS
mixin article(title)
Создаем миксин с именем article и параметром title.
И вызов:
+article('text') или
=article('text')
и возможность передавать несколько параметров.
+article('name', 'text', ...)

Precompile for frontend use

Hey! Sorry if it's inappropriate place to ask such question. Is there a way to precompile slm templates so it will be possible to use them on frontend?

We have Rails app with Backbone frontend and slim templates (skim actually) and we're trying now to move from rails infrastructure to gulp/webpack and slm looks like the only node-based engine we could use without rewriting everything. For example it could look like this.

element from variable

Can one use element (tagName) from variable.

Say you want something to be h1 or h2 depending upon semantics from the controller.

I would like to avoid long if elseif elseif ...

Vuejs event attributes

I'm trying to use event attributes in vuejs which look like this...
<a href="#" @click="doSomething()">Do Something</a>

In slm
a href="#" @click="doSomething()" Do Something doesn't work with the @

Doesn't work with new Angular 2 attribute syntax

Basically something like this:

div([value]="boundValue")

Throws a syntax error saying it is expecting an attribute. I'm assuming that is because SLM/SLIM expect [] to be used to surround attribute lists. I see no reason this can't be supported however.

Question: variables in template

I'm making gulp-slm package, and I found that the local variables which were passed not as function call contexts but as function parameters can't be used in template directly; They couldn't be used without this. prefix.

Current slm spec:

var compile = require('slm').compile;

var local = 10;
compile('p = local')();
//=> '<p>10</p>'
compile('h1 = this.title')({title: 'Hello, world!'});
//=> '<h1>Hello, world!</h1>'
compile('h1 = title')({title: 'Hello, world!'});
// ReferenceError: title is not defined

Is this intended design? If it's not, I'll make pull request for it. I feel uncomfortable from it because it wasn't like this when I worked with slim (ruby)


p.s.

Jade:

var compile = require('jade').compile;

var local = 10;
compile('p= local')();
//=> '<p>10</p>'
compile('h1= this.title')({title: 'Hello, world!'});
//=> '<h1></h1>'
compile('h1= title')({title: 'Hello, world!'});
//=> '<h1>Hello, world!</h1>'

Doesn't work with VueJS attribute syntax.

Something like this:

form @submit.prevent="createProject"

Throws Error: Text line not indented deep enough.

or

form(@submit.prevent="createProject")

Throws Error: Expected attribute

Non-shorthand syntax, like form v-on:submit="something", also does not work.
This syntax was not a problem in Slim, I've been migrating my project from Sprockets (Rails) to Webpack and I had this problem.

Dependancies

Your package.json states no dependancies, but I can find several:

grep -r 'require(' .|grep -v "'\."
./slm.js:var FS = require('fs');
./vm_node.js:var FS = require('fs');
./vm_node.js:var NodeVM = require('vm');
./vm_node.js:var Path = require('path');

I'm trying to use slm with this CMS
https://enonic.com/

Which is using thymeleaf by default. Slm is a lot slimmer :) me want.

The runtime is java, but the controllers are written in javascript.

All I really need is to slm.compile a slm file, passing in a model.object (a basic hash), and get back some html. Do I need Node VM, etc for that?

Could slm be shipped as a webjar?
http://www.webjars.org/

switch case

Can you do switch case in slm? Example code please :)

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.