12/31/2014

LiveCoder-r4 Application : Interactive environment to easily learn Coffee-Script, Jade and Stylus

# LiveCoder-r4 Application
     written for Web and JavaScript developers to easily learn and understand concept using an Interactive Environment for Coffee-Script, Jade and Stylus, ( If you want you can add other Languages too, Its FREE, Open-Source and Full-Portable), Just Download Extract and Run.

# This is not an IDE for Coffee-Script/Jade/Stylus, This just helps you to play and learn them very effectively.

#DOWNLOAD
    https://sourceforge.net/p/livecoder-r4/
    Currently I have upload binary file only for Windows Operating system, But As This tool is written using JavaFX ( Basic4Java) this will seamlessly run on any platform.

# Simple GUI Design

# Introduction to Features
     # Interactive Environment for Coffee-Script, Jade and Stylus CSS pre-processor.
    # No need to Download other binary or extra file.
    # Free, Portable and open-source, just download and install.
    # Embedded node.js binary and node package manager so that you can easily extend its features.
    # If You want, You can add support for other languages like, ( TypeScript, etc..)
    # Cross-Platform support ( Built using JavaFX ( and B4J ))

# Why use?
    # Have you ever used Coffee-Script/Jade/Stylus Language before, These are complete languages or you can say they just extends the features of their parent Languages.

    # LiveCoder gives you power to use this languages with installing and configuring anything else, Just download and extract the content to your defined Directory and you are ready to go.

    # Now browse into ${PROJECT_HOME} directory, there will be some executable files, each Built using AutoIT for Windows Operating system, these are based on my previous project ( jLauncher -> gives power to package your Java application in Fully portable manner, so that your user just download and use them, This is about running your Java application even without installing and configuring JRE . )

    # LiveCoder-r4.exe -> for running LiveCoder without CMD
    # LiveCoder-r4D.exe -> for running LiveCoder with CMD
        Helps you debug your application if anything goes wrong..
    # LiveCoder-r4-x64.exe -> for running LiveCoder without CMD  for 64-bit System.

# Getting Started
    # First download pre-built binary from sourceforge.net
    # Extract its content to any directory you want
    # Now run the executable for Livecoder as your needs.
    # Select your Language by clicking on Checkbox
        # Now click on "OPEN" button to load sample files into workspace
        # Now you can clear contents ( Using "CLEAR" button) if you want and write your own code and you can see the compilation results on fly, there is no need to save and then compile LiveCoder will Do that for you.


# So, It was so easy.

12/27/2014

Stylus : Awesome CSS Preprocessor

Stylus : CSS Preprocessor Language



= CSS Preprocessor languages (like, less, sass, SCSS, etc...) are useful to make your styles more readable and more maintainable and easier to write style sheets for complex layouts or you can build your own CSS framework like, Bootstrap ( Based on less), and Foundation ( Based on Sass).
= So, You want to learn, What Stylus is and How it is so powerful.
= Before start learning Stylus Language, let's discuss what is offers and how to use those features.



= Stylus Syntax Rules:-
=> In Stylus, you are allowed to use the Syntax of either CSS or Stylus itself.
=> If You are using Stylus syntax, then there, curly braces, semi-colons, colons are optional.

Although you can use if you like them. Stylus dropped them because it's syntax is based on Indentation, just like in Python.


=> Using stylus from Command-line
ssp@ssp-pc /media/ssp/Win/Stylus CSS Pre-processor/tuts $ stylus --help

  Usage: stylus [options] [command] [< in [> out]]
                [file|dir ...]

  Commands:

    help [<type>:]<prop> Opens help info at MDN for <prop> in
                         your default browser. Optionally
                         searches other resources of <type>:
                         safari opera w3c ms caniuse quirksmode

  Options:

    -i, --interactive       Start interactive REPL
    -u, --use <path>        Utilize the Stylus plugin at <path>
    -U, --inline            Utilize image inlining via data URI support
    -w, --watch             Watch file(s) for changes and re-compile
    -o, --out <dir>         Output to <dir> when passing files
    -C, --css <src> [dest]  Convert CSS input to Stylus
    -I, --include <path>    Add <path> to lookup paths
    -c, --compress          Compress CSS output
    -d, --compare           Display input along with output
    -f, --firebug           Emits debug infos in the generated CSS that
                            can be used by the FireStylus Firebug plugin
    -l, --line-numbers      Emits comments in the generated CSS
                            indicating the corresponding Stylus line
    -m, --sourcemap         Generates a sourcemap in sourcemaps v3 format
    --sourcemap-inline      Inlines sourcemap with full source text in base64 format
    --sourcemap-root <url>  "sourceRoot" property of the generated sourcemap
    --sourcemap-base <path> Base <path> from which sourcemap and all sources are relative
    -P, --prefix [prefix]   prefix all css classes
    -p, --print             Print out the compiled CSS
    --import <file>         Import stylus <file>
    --include-css           Include regular CSS on @import
    -D, --deps              Display dependencies of the compiled file
    --disable-cache         Disable caching
    -r, --resolve-url       Resolve relative urls inside imports
    -V, --version           Display the version of Stylus
    -h, --help              Display help information

  

=>> You can use Stylus interactive REPL shell, that is great to play with Stylus functions.


ssp@ssp-pc ~ $ stylus -i
> 
aliceblue                    antiquewhite                 aqua                         aquamarine                   azure
beige                        bisque                       black                        blanchedalmond               blue
blueviolet                   brown                        burlywood                    cadetblue                    chartreuse
chocolate                    coral                        cornflowerblue               cornsilk                     crimson
cyan                         darkblue                     darkcyan                     darkgoldenrod                darkgray
darkgreen                    darkgrey                     darkkhaki                    darkmagenta                  darkolivegreen
darkorange                   darkorchid                   darkred                      darksalmon                   darkseagreen
darkslateblue                darkslategray                darkslategrey                darkturquoise                darkviolet
deeppink                     deepskyblue                  dimgray                      dimgrey                      dodgerblue
firebrick                    floralwhite                  forestgreen                  fuchsia                      gainsboro
ghostwhite                   gold                         goldenrod                    gray                         green
greenyellow                  grey                         honeydew                     hotpink                      indianred
indigo                       ivory                        khaki                        lavender                     lavenderblush
lawngreen                    lemonchiffon                 lightblue                    lightcoral                   lightcyan
lightgoldenrodyellow         lightgray                    lightgreen                   lightgrey                    lightpink
lightsalmon                  lightseagreen                lightskyblue                 lightslategray               lightslategrey
lightsteelblue               lightyellow                  lime                         limegreen                    linen
magenta                      maroon                       mediumaquamarine             mediumblue                   mediumorchid
mediumpurple                 mediumseagreen               mediumslateblue              mediumspringgreen            mediumturquoise
mediumvioletred              midnightblue                 mintcream                    mistyrose                    moccasin
navajowhite                  navy                         oldlace                      olive                        olivedrab
orange                       orangered                    orchid                       palegoldenrod                palegreen
paleturquoise                palevioletred                papayawhip                   peachpuff                    peru
pink                         plum                         powderblue                   purple                       red
rosybrown                    royalblue                    saddlebrown                  salmon                       sandybrown
seagreen                     seashell                     sienna                       silver                       skyblue
slateblue                    slategray                    slategrey                    snow                         springgreen
steelblue                    tan                          teal                         thistle                      tomato
turquoise                    violet                       wheat                        white                        whitesmoke
yellow                       yellowgreen                  rebeccapurple                called-from                  vendors
-string(arg)                 require-color(color)         require-unit(n)              require-string(str)          abs(n)
min(a, b)                    max(a, b)                    PI                           radians-to-degrees(angle)    degrees-to-radians(angle)
sin(n)                       cos(n)                       ceil(n, precision)           floor(n, precision)          round(n, precision)
sum(nums)                    avg(nums)                    remove-unit(n)               percent-to-decimal(n)        odd(n)
even(n)                      light(color)                 dark(color)                  desaturate(color, amount)    saturate(color, amount)
darken(color, amount)        lighten(color, amount)       fade-out(color, amount)      fade-in(color, amount)       spin(color, amount)
mix(color1, color2, weight)  invert(color)                complement(color)            grayscale(color)             tint(color, percent)
shade(color, percent)        last(expr)                   keys(pairs)                  values(pairs)                join(delim, vals)
add-property-function        add-property(name, expr)     prefix-classes(prefix)       $stylus_mixin_cache          cache()

> red(#fff)
=> 255
> 
      
    

=>> You can write a full Stylus code to Terminal and Stylus compile that and print to terminal. First run Stylus executable and then write your stylus code to terminal, when complete HIT the CTRL-D key, now you can see the compiled output. This technique is basically same as that (php -a) (PHP Interactive mode)

ssp@ssp-pc ~ $ stylus 
body
  color red
  font 14px Arial, sans-serif

body {
  color: #f00;
  font: 14px Arial, sans-serif;
}

ssp@ssp-pc ~ $ 
    
  

=>> If you want help regarding any CSS property, then you can use, This will open up a browser with a reference to that property from Mozilla website.
    stylus help box-shadow    // this works in Linux/Unix
 
=>> If you want to use any external stylus style-sheet, then stylus must know about it, so add the path to Stylus lookup path using --include flag.
     $ stylus < test.styl --include ../nib/lib    

=> first learn the theory of Stylus and then we will take a look at its examples and demos.

= Comments in Stylus Style-sheet ( In compressed CSS comments and white-space will be removed.)
    = Single line comments
( just like a JavaScript comments ( using '//' ), and will not be in resulting CSS)
    = Multi-line Comments
( just like a regular CSS multi-line comment ( using '/* This is a CSS comment*/'))
    = Multi-line buffered Comments
( Just like multi-line comments, but start with '/*! This is a buffered comment */')
        = Multi-line buffered comment will be there in output CSS even if you had passed a compress flag for Stylus compiler.

= Defining ans using variable in Stylus Style-sheet (So, that you can use them later)
    = A Stylus variable may be a single value (like, font = 12px) or a expression (like, font = "sans") or a expression list (like, font = 15px, "sans-serif")
    = You can use a '$' prefix for Stylus variable name or functions names (like, $font = "sans-serif")

= Property reference ( Using the '@' operator)
    = Stylus has a awesome feature so that you can refer properties defined earlier without defining the variable.
    = Just append the '@' character before the Property name that you want to refer.
    = returns  'nil'  if property does not exists.

= Using CSS selectors and how to nesting of Selectors works
    = Stylus use Indentation instead of curly-braces.
    = You can nest as many as selectors you want.
    = You can use multiple selectors at a time either use a comma ',' to separate them or in Stylus you can use a newline character.

= Parent Selectors Reference using '&' Operator
    = You can refer to parent selectors using '&' operator.
    = There may be one or more than one parent selectors based on Scope.
    = Understand the difference between the indented parent selectors and parent selectors separated using Comma or newline.
    = Indentation means nested selectors, and newline ( or comma) means multiple selectors.

= Root Selector Reference using '/' operator
   = This is simply tell us, protect this selector from parent reference, use this as root context.

= Using selector() built-in function
    = this built-in function returns the current compiled selector that can be used inside a mixin or function.

= Using the unquote() built-in function
    = this return the value without quote, so that Stylus can process that values.

= Using Stylus built-in Operators (addition, subtraction, etc...)
    = Unary Operators ( !, not, -, +, ~  )
    = Binary Operators
        = Additive ( +, -  )
        = Multiplicative ( /, *, %  )
        = Exponent ( **)
        = Equality and Relational ( ==, !=, <=, >=, >, <  )
        = Logical Operator ( &&, ||, and, or  )
        = Existence Operator ( in  )
        = Conditional Assignment
 ( if variable exists than there is no need to reassign variable)
          = These are equivalent.
          color := white
          color ?= white
          color  = color is defined ? color : white

        = Instance check ( is a )
( example, 15 is a 'unit') ( means we are checking that does 15 belongs to unit class)
        = Variable Definition ( is defined  ) ( Does this variable is defined earlier)
        = Ternary Operator ( $a = (conditional_expression) ? true : false  )
        = Color Operations
( rgb() or rgba() built-in function) (or we can simply use +, -, *, 12%, 45deg etc... operations)
        = s() built-in function ( using '%' operator) ( same as sprintf() function is C/C++)
          'X::Microsoft::Crap(%s)' % #fc0
          // => X::Microsoft::Crap(#fc0)

        = subscript Operator "[]" 
( allow you to grab a value via index ( Zero-based), and negative index means start from end)
          list = 1 2 3 4 5 6
          tuple = (1 2 3 4)
          tuple = (100px 200px)
          list[0]
          // 1
        = Inclusive and Exclusive Ranges
          1..5
          // 1 2 3 4 5
          1...5
          // 1 2 3 4
          5..1
          // 5 4 3 2 1


= Stylus Interpolation Rules
    = Stylus supports interpolation by using the {} characters to surround an expression.
    = values inside this braces will be treated as Identifier.

= Conditionals statements (like, if, if else, unless  )
    = unless is basically opposite of  if  statement, and equal to  if(!(condition_expression))
    = Post-fix Conditionals
        = note that  if and  unless both works as operator, means when right-hand expression/operand is truthy, they evaluates the left hand-expression/operand. this helps us to write one line conditional expressions.

= Using Hashes in Stylus (like, Dictionary in Python )
    = You can define a hash using curly braces and comma to separate keys and values, note that keys should be either proper indented or a string value.
    = if you want to add any key/value pair to pre-defined hash, then you can use brackets with string key.
    = To get a value of any key from Hash you can use a dot (.) operator with hash name.
    = hashes used inside a curly braces (means for interpolation) just returns hash values that can be used as CSS rules.
    = Built-in length()  function just returns its length.
    = keys() and values() built-in functions, just returns a list of keys and values respectively.
    = merge() or extend()  are used to merge two hashes.
   

= Iteration or Loop functions in Stylus (like, for )
    = Stylus Allow you to iterate expressions using for/in construct
    = Syntax:-
      for <value_name> [, <key_name>] in <expression>
     
      body
        for num in 1 2 3 4
          foo num
         
      body
        for num in (1..5)
          foo num
   
    = Note that likewise if/unless,  for also behaves  post-fix operator.

= Using Mixins in Stylus style-sheets ( reusable block of CSS code that can optionally take parameters)
    = Both mixins and functions are defined in same manner, but they are applied in different ways.
    = When mixin is invoked within a selector, the properties are expanded and copied into the selector.
    = Stylus Introspection API, Whenever you call a mixin, then a local variable name 'mixin' is automatically created with a string value 'root', this help you to find whether a function is invoked as a mixin or as a function.

= Using Transparent Mixins ( Mixins with unknown number of parameters )
    = mixin defined without any parameters but uses the local variable 'arguments' variable that contain expression passes to it.
    = thus allowing multiple values to be passed.

= Using Block Mixins
    = You can pass blocks to mixins by calling the mixin with  +  prefix.
    = use a local variable  'block'  inside curly brackets to access passed blocks.

= Nesting Mixins inside Mixins
    = Mixins can utilize other mixins, build upon their own selectors and properties.
   
   
= Defining and Using Functions ( function that can return a value )
    = Function that can return value
    add(a,b)
      a + b
     
    = Functions with default arguments
    add(a, b=a)  // b = a until you explicitly define a value for b
      a + b
     
    = Functions with named parameters
    subtract(a, b)
      a - b
     
    subtract(b: 10, a: 25)
   
    = Function that returns multiple values
      = Stylus functions can return multiple values as you assign multiple value to a variable.
      sizes = 15px 10px  // Stylus variable with multiple values
     
      sizes()    // stylus function that return multiple values
        15px 10px
      = While returning multiple values from function either use parenthesis for values or use a return statement before them.

    = Function with different name ( function Aliasing)
    plus = add
   
    plus(1,2)  // returns 3
   
    = Stylus Anonymous functions ( Using '@() {}' syntax)

    = local variable 'arguments' is available to all function bodies, and contain all the arguments passed.


= Functions with Rest parameters (like, curry functions in Haskell)
    = Stylus supports rest parameters in the form of   'name...'  These params consume the remaining arguments passed to a mixin or function.

= Stylus Built-in Functions for you ( In Stylus there are over 60 Built-in function for you to use)
    = red(color[, value])
      return the red component of the given color, or set the red component to given value.
    = green(color[, value])
      return the green component of the given color, or set the green component to given value.
    = blue(color[, value])
      return the blue component of the given color, or set the blue component to given value.
    = alpha(color[, value])
      return the alpha component of the given color, or set the alpha component to given value.
    = dark(color)
      check if color is dark
    = light(color)
      Check if color is light
    = hue(color[, value])
      Return the hue of the given color or set the hue component to the optional argument value.
    = saturation(color[, value])
      Return the saturation of the given color or set the saturation component to the optional argument value.
    = lightness(color[, value])
      Return the lightness of the given color or set the lightness component to the optional argument value.
    = push(expr, args...)
      Push the given  args to expr
    = unshift(expr, args...)
      Unshift the given args to expr
    = keys(pairs)
      Return keys in the given pair
    = values(pairs)
      Return the values in given pair
    = list-separator(list)
      Return the separator of the given list (for example, white-space, or a comma)
    = typeof(node)
      Return the type of node as a string
    = unit(unit[, type])
      Return a string for the type of unit or an empty string, or assign the given type without unit conversion.
      unit(15in)    // returns 'in' [inch]

    = match(pattern, string)
      Test if string matches the given pattern
    = abs(unit)  // absolute value
    = ceil(unit)  // nearest upper integer
    = floor(unit)  // nearest lower integer
    = round(unit[, precision])
    = sin(angle)
      without any unit angle will be assumed as radians, you can explicitly use degrees as 45deg
    = cos(angle)
    = tan(angle)
    = min(a, b)  // comma separated two values
    = max(a, b)
    = even(unit)
    = odd(unit)
    = sum(nums)
      supply a white-space separated list of numbers
    = avg(nums)
    = base-convert(num, base, width)
      num, that you want to convert, base, with this base, and with this width
    = join(delim, vals...)
    = hsla(color | h,s,l,a)
      Convert the given color to an HSLA node or h, s, l ,a component values.
    = hsl(color | h, s, l)
    = rgba(color | r,g, b, a)
      Return RGBA from the r, g, b, a channels or provide a color to tweak the alpha.
    = rgb(color | r, g, b)
    = blend(top[, bottom])
      Blends the given top color over the bottom one using the normal blending. The bottom argument is optional and is defaulted to #fff
    = lighten(color, amount)
      Lighten the given color by amount. This function is unit-sensitive. for example supporting percentages.
    = darken(color, amount)
      Darken the given color by amount, This function is unit-sensitive, for example supporting percentages.
    = desaturate(color, amount)
      Desaturate the given color by amount.
    = saturate(color, amount)
      Saturate the given color by amount.
    = complement(color)
      Gives the complementary color  Equals to spinning HUE to 180deg.
    = invert(color)
      Inverts the color. The red, green, and blue values are inverted, while the opacity is left alone.
    = grayscale(color)
      Gives the grayscale equivalent of the given color, Equals to desaturate by 100%
    = tint(color, amount)
      Mix the given color with white.
    = shade(color, amount)
      Mix the given color with black.
    = luminosity(color)
      Returns the relative luminance of the given color.
    = constrast(top[, bottom])
      Returns the contrast ratio object between top and bottom colors,
      The second argument is optional and is defaulted to #fff.
   
    = transparentify(top[, bottom, alpha])
      Returns the transparent version of the given top color, as if it was blend over the given bottom color
      The second argument is optional and is defaulted to #fff.

    = unquote(str | ident)
      Unquote the given str and returned as a Literal node.

    = convert(str)
      Like unquote() but tries to convert the given str to a Stylus node.
     
    = s(fmt, ...)
    = basename(path[, ext])
      Returns the basename of path, (optionally) with ext extension removed.
    = dirname(path)
      Returns the dirname of path
    = extname(path)
      Return the filename extension of path including the dot
    = pathjoin(...)
      Perform a path join
   
    = called-from   property
      called-from property contains the list of the functions the current function was called from in the reverse order (the first item is the deepest function).

    = current-media()
      returns the string of the current block’s @media rule or '' if there is no @media above the block.
     
    = +cache(keys...)
      allows you to create your own “cachable” mixins.
    = +prefix-classes(prefix)
      Stylus comes with a block mixin prefix-classes that can be used for prefixing the classes inside any given Stylus’ block
     
    = lookup(name)
      Allows to lookup a variable with a given name, passed as a string. Returns null if the variable is undefined.
    = define(name, expr)
      Allows to create or overwrite a variable with a given name, passed as a string, onto current scope.
    = operate(op, left, right)
      Perform the given op on the left and right operands
    = length([expr])
    = selector()
      Returns the compiled current selector or & if called at root level.
    = warn(msg)
      Warn with the given error msg, does not exit.
    = error(msg)
      Exits with the given error msg.
    = last(expr)
      Return the last value in the given expr
    = p(expr)
      Inspect the given expr
    = opposite-position(positions)
      Return the opposites of the given positions.
    = image-size(path)
      Returns the width and height of the image found at path
    = add-property(name, expr)
      Adds property name, with the given expr to the closest block.
    = use(path)
      You can use any given js-plugin at given path with use() function right inside your ‘.styl’ files
    = Undefined Functions
      Undefined functions will output as literals   

@import and @require
    = Using @import statement you can import either standard CSS file or a stylus style-sheet.
    @import 'mystyle.css'    // for importing standard CSS file
    @import 'mystyle'        // without extension, assuming you want to import Stylus style-sheet
   
    = @import  works by iterating an array of directories, and checking if this file lives in any of them. This array defaults to a single path, which is derived from the 'filename' option's  dirname'
    = @require works same as @import statement, but you can require a file only once.
    = Stylus supports block level import, means you can use @import  not only at root level, but also nested inside other selectors or at-rules.
    = @import multiple files at once, using FILE GLOBING ( Using a mask)
    @import 'product/*'

@media
    = The @media queries work the same way as in standard CSS, But in Stylus you can use them using Stylus Syntax.
    = Nesting Media queries, ( Media Query Bubbling), when expanded they wrap the context in which they are used.
    .width
        padding 10px
       
        @media screen and (min-width: 600px)
            padding 20px
           
    .width {
        padding: 10px;
    }
    @media screen and (min-width: 600px) {
        .width {
            padding: 20px;
        }
    }
       
       
@font-face
    = Allows you to define your own font rules.

@keyframes
    = works as same in CSS3, This is basically CSS3 based technique to create animations without any JavaScript Code.
    = You need a @ rule with an Identifier in this case, that is 'keyframes' and some nested rules sets for frames.
    = In Stylus you can use loops/Interpolation/Variable that helps you a lot.

    $keyframe-name = pulse    //This is our animation name
    @keyframes {$keyframe-name}
      for i in 0..10
        {10% * i}
          opacity (i/10)

= Other @-Stylus rules
    = their is nothing special about CSS3 'at rules', use them as you use there is CSS3, but you can use nesting/Interpolation/Loops/Conditions/variables.

@extend ( Inherit CSS rules from other selector or Mixins)
    = You can extend pre-existing Selector or nested one.
    = You can extend multiple selectors, just separate them using comma.
    = Extending placeholder selectors, name starts with a '$'  character and not yielded in the resulting CSS, but you can still extend them. They offers you a powerful way to create your own libraries, and still compact output.

@block
    = Assigning a name for a block of code and use them later, either pass it to function or use in Interpolation expression.
    foo =
        width: 20px
        height: 20px
       
    foo @block {
        width: 20px
        height: 20px
    }

= url()
    = This function replaces the literal url() function inside CSS. This allow you to conditionally inline them using base64 Data URLs.
    = Limit bytesize limit defaulting to 30kb, use false to disable it.

= CSS Literal
    = if there is some code that you want to write in literal CSS, you can always use Stylus @css tag with wrapped CSS rules inside parenthesis.
    @css {
        body {
            font: 14px;
        }
    }

= CSS Style Syntax ( we can mix CSS style code and Stylus style code)
= Character Escaping (use  '\'  character to escape any character)

= Connect Middleware ( useful in Express )
    = what is a Middleware?
        = So, you got a request, but there is a Middleware defined for response, so, Middleware will get executed before processing the actual request and returning response.
    = for auto-Compiling the Stylus sheets whenever modified.
   
= CSS3 Extensions with Nib ( library with useful Stylus mixins and functions)
    = Stylus mixins, utilities, components, and gradient image generation.
   
= JavaScript API
    = Simply  require  the module and call render() with the given Stylus code and optional 'options' Object.
    .set(setting, value)
        = Apply settings such as 'filename' or import 'paths'
       
    .include(path)
        = An alternative to .set('paths', ...) is include() , this is ideal for when exposing external Stylus libraries which expose a path.
       
    .import(path)
        = Dynamically import a stylus library file for your code.
       
    .define(name, node)
        = This is useful for defining Global variable that may help you to dynamically generate style sheet.
       
    .define(name, fn)
        = This allows you to define a JavaScript function to Stylus, this if for you when there is something that you can not do directly in Stylus but you can do using JavaScript.
    .use(fn)
        = when called the given function 'fn' is invoked with renderer, allowing all of the methods above to be used.


=> This is a Simple Example of Stylus using CSS Syntax.
//- FILE:  mystyle.styl
body {
  font: 14px/1.5 Helvetica, Arial, sans-serif;
  #logo {
    border-radius: 15px;
  }
}
  =>> In This example we nest selectors.

//- FILE:  mystyle.css
body {
  font: 14px/1.5 Helvetica, arial, sans-serif;
}
body #logo {
  border-radius: 15px;
}



=> Stylus Syntax
  If you want to select multiple selectors, just put them on a newline or use comma to separate them.

//- FILE: mystyle.styl
body
  font 14px/1.4 Helvetica, arial, sans-serif
  button
  button.button
  input[type='button']
  input[type='submit']
    border-radius 5px

//- FILE:  mystyle.css
body {
  font: 14px/1.4 Helvetica, arial, sans-serif;
}
body button,
body button.button,
body input[type='button'],
body input[type='submit'] {
  border-radius: 5px;
}

=> Parent Reference (So, You want to use its parent for this style)
    There are two syntax for referring parent selectors,
    use  &  after the pre-defined selectors.
      So, that all parent will be nested after your defined selector.
    use  &  before the pre-defined selectors.
      So, that all parents will be nested before your defined selector.

//- FILE:  mystyle.styl
ul
  li a
    display block
    color blue
    padding 5px
    html.ie &
      padding 6px
    &:hover
      color red

//- FILE:  mystyle.css
ul li a {
  display: block;
  color: #00f;
  padding: 5px;
}
html.ie ul li a {
  padding: 6px;
}
ul li a:hover {
  color: #f00;
}

=> Mixins (So, you want to define your own CSS templates)
    Mixins are reusable blocks of code that can optionally take arguments.

//- FILE:  mystyle.styl
border-radius(val)
  -webkit-border-radius val
  -moz-border-radius val
  border-radius val

button
  border-radius(5px)

//- FILE:  mystyle.css
button {
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}


=> Transparent Mixins (Mixin with unknown number of parameters)

    Transparent Mixins are unique to Stylus, and are great powerful way to enhance your style-sheets, Here all parameters passed are simply assigned to three properties.

//- FILE:  mystyle.styl
border-radius()
  -webkit-border-radius arguments
  -moz-border-radius arguments
  border-radius arguments

button
  border-radius 5px 10px

//- FILE: mystyle.css
button {
  -webkit-border-radius: 5px 10px;
  -moz-border-radius: 5px 10px;
  border-radius: 5px 10px;
}

=> Variables (So, you want to define and use variables in Stylus)

    Stylus variables behaves as you would expect in any other language and may be optionally be prefixed by the  "$"  character.

//- FILE:  mystyle.styl
#prompt
  position absolute
  top 150px
  left 50%
  width $w = 200px
  margin-left -($w / 2)

//- FILE:  mystyle.css
#prompt {
  position: absolute;
  top: 150px;
  left: 50%;
  width: 200px;
  margin-left: -100px;
}

=> Block property access (So, You want to access some pre-defined values in current code block)
    Stylus property access provides easy access to values defined within the current block. Simply prefix the name of property with "@" to reference the value.

//- FILE:  mystyle.styl
#prompt
  position absolute
  top 150px
  left 50%
  width 200px
  margin-left -( @width / 2 )

//- FILE:  mystyle.css
#prompt {
  position: absolute;
  top: 150px;
  left: 50%;
  width: 200px;
  margin-left: -100px;
}

=> Robust feature rich language
    Lets use the concept of transparent mixins and Stylus built-in functions and rich features.
    You can write cross-browser supported CSS.

//- FILE:  mystyle.styl
-pos(type, args)
  i = 0
  position unquote(type)
  {args[i]} args[i + 1] is a 'unit' ? args[i += 1] : 0
  {args[i += 1]} args[i + 1] is a 'unit' ? args[i += 1] : 0

absolute()
  -pos('absolute', arguments)

fixed()
  -pos('fixed', arguments)

#prompt
  absolute top 150px left 5px
  width 200px
  margin-left -(@width / 2)

#logo
  fixed top left

//- FILE:  mystyle.css
#prompt {
  position: absolute;
  top: 150px;
  left: 5px;
  width: 200px;
  margin-left: -100px;
}
#logo {
  position: fixed;
  top: 0;
  left: 0;
}

=> List Iteration in Stylus

//- FILE:  mystyle.styl
table
  for row in 1 2 3 4 5
    tr:nth-child({row})
      height 10px * row

//- FILE:  mystyle.css
table tr:nth-child(1) {
  height: 10px;
}
table tr:nth-child(2) {
  height: 20px;
}
table tr:nth-child(3) {
  height: 30px;
}
table tr:nth-child(4) {
  height: 40px;
}
table tr:nth-child(5) {
  height: 50px;
}

=> Interpolation

//- FILE:  mystyle.styl
vendores = webkit moz o ms official

border-radius()
  for vendor in vendors
    if vendor == official
      border-radius arguments
    else
      -{vendor}-border-radius arguments

#content
  border-radius 5px

//- FILE:  mystyle.css
#content {
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  -o-border-radius: 5px;
  -ms-border-radius: 5px;
  border-radius: 5px;
}

=> Stylus Built-in Operators
//- FILE:  mystyle.styl
body
  foo 5px + 10
  foo 2 ** 8
  foo 5px * 2
  foo foo and bar and baz
  foo foo or bar or baz
  foo 1..5
  foo 1...5
  foo 'foo' is a 'string'
  foo (1 2 3) == (1 2 3)
  foo (1 2 3) == (1 2)
  foo ((one 1) (two 2)) == ((one 1) (two 2))
  foo ((one 1) (two 2)) == ((one 1) (two))
  foo 3 in (1 2 3 4)

//- FILE:  mystyle.css
body {
  foo: 15px;
  foo: 256;
  foo: 10px;
  foo: baz;
  foo: foo;
  foo: 1 2 3 4 5;
  foo: 1 2 3 4;
  foo: true;
  foo: true;
  foo: false;
  foo: true;
  foo: false;
  foo: true;
}

=> Style Type coercion feature
//- FILE:  mystyle.styl
body
  foo foo + bar
  foo 'foo' + bar
  foo 'foo' + 'bar'
  foo 'foo' + 5px
  foo 2s - 500ms
  foo 5000ms == 5s
  foo 50deg

//- FILE:  mystyle.css
body {
  foo: foobar;
  foo: 'foobar';
  foo: 'foobar';
  foo: 'foo5px';
  foo: 1.5s;
  foo: true;
  foo: 50deg;
}

=> Stylus sprintf Operator
    The powerful "%" Operator when used with strings behaves like sprintf with each argument compiled through the stylus compiler, producing a literal value.

//- FILE:  mystyle.styl
body
  foo '%s / %s' % (5px 10px)
  foo 'MS:WeirdStuff(opacity=%s)' % 1
  foo unquote('MS:WeirdStuff(opacity=1)')

//- FILE:  mystyle.css
body {
  foo: 5px / 10px;
  foo: MS:WeirdStuff(opacity=1);
  foo: MS:WeirdStuff(opacity=1);
}

=> Stylus Color Operations
    Operations against colors are especially useful when adding or subtracting by a percentage the color lightness may be adjusted, or the hue may be adjusted with deg.

//- FILE:  mystyle.styl
body
  foo white - 50%
  foo black + 50%
  foo #eee - #f00
  foo #eee - rgba(black, .5)
  foo #cc0000 + 30deg

//- FILE:  mystyle.css
body {
  foo: #808080;
  foo: #808080;
  foo: #0ee;
  foo: rgba(238,238,238,0.5);
  foo: #c60;
}

=> Stylus Functions
    Stylus Functions may be defined in the same manner as mixins, however their usage differs as they return values.

//- FILE:  mystyle.styl
sum(nums...)
  n = 0
  n += num for num in nums

body
  foo sum(1,2,3,4)

//- FILE:  mystyle.css
body {
  foo: 10;
}

=> Stylus Functions with Keyword arguments

//- FILE:  mystyle.styl
fade-out(color, amount=50%)
  color - rgba(0,0,0,amount)

body
  foo fade-out(#eee)
  foo fade-out(#eee, 20%)
  foo fade-out(#eee, amount=40%)
  foo fade-out(#eee, amount: 40%)
  foo fade-out(color: #eee, amount=40%)
  foo fade-out(amount: 40%, color: #eee)

//- FILE:  mystyle.css
body {
  foo: rgba(238,238,238,0.5);
  foo: rgba(238,238,238,0.8);
  foo: rgba(238,238,238,0.6);
  foo: rgba(238,238,238,0.6);
  foo: rgba(238,238,238,0.6);
  foo: rgba(238,238,238,0.6);
}

=> Stylus Built-in Functions
    Stylus is packed with over 60 built-in functions for manipulating colors, checking variable types, math, list operations, and many more.

//- FILE:  mystyle.styl
body
  foo red(#fc0)
  foo green(#fc0)
  foo blue(#fc0)
  foo alpha(#fff)
  foo alpha(rgba(#fff, .5))

//- FILE: mystyle.css
body {
  foo: 255;
  foo: 204;
  foo: 0;
  foo: 1;
  foo: 0.5;
}

=> Stylus Color BIFs
    The Color built-in functions allow you to adjust lightness, hue, and saturation, check if colors are light or dark or more.

//- FILE:  mystyle.styl
body
  foo light(#eee)
  foo dark(#eee)
  foo dark(#333)
  foo darken(#eee, 50%)
  foo lighten(black, 50%)
  foo #eee - 50%
  foo black + 50%

//- FILE:  mystyle.css
body {
  foo: true;
  foo: false;
  foo: true;
  foo: #777;
  foo: #808080;
  foo: #777;
  foo: #808080;
}

 

12/25/2014

All about Jade: Template Engine for Node

# What is Jade?
    # Jade is a Template Engine for Node.js
    # Jade is default Template Engine for Express ( Node.js web framework)
    # Jade is a high performance template engine heavily influenced by Haml (http://haml-lang.com)
       and implemented with JavaScript for [ Node ].
    # You can imagine a Jade Template as a View for your Node.JS application, for example,
        You can put all of your JavaScript Code/Logic inside a index.js file, This file can export
        JavaScript Objects, Variable, and other data type,
        and Your Jade Template can use those things to setup/generate a static HTML web page, using optional
        export data from node.js app (In this case, index.js)
    # If you are familiar with Python/Haskell/Coffee-script etc,, they use Indentation for nesting of expressions,
        same as for Jade, Here we use 2 white-space as indentation for Jade expressions to nest them into one another.

# How to Install?
    # Using node package manager ( npm )
        npm install jade -g

# Jade API ( using jade inside Node project )
     # import jade using require() function

    # All API options that can be used while compiling or rendering Jade Template
{
    filename:  'string',
    doctype: 'string',
    pretty:  'boolean|string',
    self:  'boolean',
    debug:  'boolean',
    compileDebug:  'boolean',
    compiler:  'class',
    globals: Array<string>
}

       var jade = require('jade')

> require('jade')
{ selfClosing:
[ 'area',
'base',
'br',
'col',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'menuitem',
'meta',
'param',
'source',
'track',
'wbr' ],
doctypes:
{ default: '<!DOCTYPE html>',
xml: '<?xml version="1.0" encoding="utf-8" ?>',
transitional: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
strict: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
frameset: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'1.1': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
basic: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
mobile: '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">' },
filters: [Function: filter],
utils:
{ merge: [Function],
walkAST: [Function: walkAST] },
Compiler: [Function: Compiler],
Parser: [Function: Parser],
Lexer: [Function: Lexer],
nodes:
{ Node: [Function: Node],
Tag: [Function: Tag],
Code: [Function: Code],
Each: [Function: Each],
Case: { [Function: Case] When: [Function: When] },
Text: [Function: Text],
Block: [Function: Block],
MixinBlock: [Function: MixinBlock],
Mixin: [Function: Mixin],
Filter: [Function: Filter],
Comment: [Function: Comment],
Literal: [Function: Literal],
BlockComment: [Function: BlockComment],
Doctype: [Function: Doctype] },
runtime:
{ merge: [Function: merge],
joinClasses: [Function: joinClasses],
cls: [Function: cls],
attr: [Function: attr],
attrs: [Function: attrs],
escape: [Function: escape],
rethrow: [Function: rethrow] },
cache: {},
compile: [Function],
compileClient: [Function],
compileFile: [Function],
render: [Function],
renderFile: [Function],
compileFileClient: [Function],
__express: [Function] }


# compile
    var fn = jade.compile('string of jade', options);
    var html = fn(locals);
ssp@ssp-pc ~ $ node
    > var jade = require('jade')
    > var fn = jade.compile('doctype html')
    > var html = fn()
    > html
        '<!DOCTYPE html>'

# render
    var html = jade.render('string of jade', merge(options, locals));

    > var html = jade.render('doctype html\nhtml(lang="eng")')
    > html
        '<!DOCTYPE html><html lang="eng"></html>'

# render jade file
    var html = jade.renderFile('filename.jade', merge(options, locals));

    # demo.jade
doctype html
html
  head
    title #{title}
  body
    h1 This is #{title}
    p This is very simple paragraph


    # jade template rendering
> var html = jade.renderFile('demo.jade', ('pretty', {title: 'Simple Node jade template'}))
> console.log(html)
<!DOCTYPE html>
<html>
<head>
<title>Simple Node jade template</title>
</head>
<body>
<h1>This is Simple Node jade template</h1>
<p>This is very simple paragraph</p>
</body>
</html>


# Using jade from Command line
# jade Synopsis
  Usage: jade [options] [dir|file ...]

  Options:

    -h, --help         output usage information
    -V, --version      output the version number
    -O, --obj <str>    javascript options object
    -o, --out <dir>    output the compiled html to <dir>
    -p, --path <path>  filename used to resolve includes
    -P, --pretty       compile pretty html output
    -c, --client       compile function for client-side runtime.js
    -n, --name <str>   The name of the compiled template (requires --client)
    -D, --no-debug     compile without debugging (smaller functions)
    -w, --watch        watch files for changes and automatically re-render
    --name-after-file  Name the template after the last section of the file path (requires --client and overriden by --name)
    --doctype <str>    Specify the doctype on the command line (useful if it is not specified by the template)

  Examples:

    # translate jade the templates dir
    $ jade templates

    # create {foo,bar}.html
    $ jade {foo,bar}.jade

    # jade over stdio
    $ jade < my.jade > my.html

    # jade over stdio
    $ echo 'h1 Jade!' | jade

    # foo, bar dirs rendering to /tmp
    $ jade foo bar --out /tmp 


# compile Jade template using command line
jade --client --no-debug filename.jade

which will produce filename.js containing the compiled template.

ssp@ssp-pc ~ $ /usr/local/bin/jade --pretty demo.jade

  rendered demo.html

ssp@ssp-pc ~ $ cat demo.html
<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body>
    <h1>This is </h1>
    <p>This is very simple paragraph</p>
  </body>
</html>ssp@ssp-/usr/local/bin/jade demo.jade

  rendered demo.html

ssp@ssp-pc ~ $ cat demo.html
<!DOCTYPE html><html><head><title></title></head><body><h1>This is </h1><p>This is very simple paragraph</p></body></html>ssp@ssp-pc ~ $ 


# Document type declaration inside Jade document

doctype html
<!DOCTYPE html>

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

doctype transitional
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.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 1.1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

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

doctype mobile
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">

    =>Custom Doctypes
You can also use your own literal custom doctype:

doctype html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN">

    => Using doctype as an Option while compiling and rendering, and see its effect.
The doctype affects compilation in some other cases, for example self closing tags and boolean attributes).
For this reason, you might sometimes want to specify it manually. You can do this via the doctype option. e.g.

var jade = require('jade');    // importing Jade module as jade variable

// Compile a function, with doctype as XML
var fn = jade.compile('img(src="foo.png")', {doctype: 'xml'});

// Render the function
var html = fn({});
    '<img src="foo.png"></img>'

// Compile a function, with doctype as HTML
var fn = jade.compile('img(src="foo.png")', {doctype: 'html'});

// Render the function
var html = fn({});
    '<img src="foo.png">'


# Writing comments for either Jade Template or for generated HTML document
    => Single line comments look the same as JavaScript comments and must be
           placed on their own line.

// just some paragraphs
p foo
p bar
<!-- just some paragraphs -->
<p>foo</p>
<p>bar</p>

    => Jade also supports un-buffered comments, by simply adding a hypen

- // This is a JavaScript expression comment
//- Simple java-script


    => Block Comments ( means a multi-line comment for HTML document)

body
  //
    As much text as you want
    can go here

<body>
  <!--
  As mush text as you want
  can go here
  -->
</body>

    => Conditional Comments
Jade does not have any special syntax for conditional comments. If your line begins with <
then it is treated as plain text. So just use normal HTML style conditional comments

<!--[if IE 8]>
<html lang="en" class="it-ie9">
<![endif]-->


# Writing Plain text for Jade, that will not be processed by Jade Compiler
    => Jade provides three common ways of getting plain text,

    => Piped Text, prefix the line with  |  character.

body
  | Plain text can include <strong>HTML</strong>
  br
  | because This piped text will be passed as it was.
  p
    | It must always be on its own line


<body>Plain text can include <strong>HTML</strong><br/>because This piped text will be passed as it was.
  <p>It must always be on its own line</p>
</body>

    => Inline in a Tag
since it's a common use case, you can put text in a tag just by adding it inline after a space

p Plain text can include <strong>html</strong>

<p>Plain text can include <strong>html</strong></p>

    => Block in a Tag, useful for writing JavaScript and CSS rules inside Jade Template.
Often you might want large blocks of text within a tag. A good example is with inline scripts or styles.
To do this, just add a  .  after the tag (with no preceding space)

script(src="java.js").
  if (usingJade())
    console.log("you are awesome")
  else
    console.log("use Jade")

<script src="java.js">
  if (usingJade())
    console.log("you are awesome")
  else
    console.log("use Jade")
</script>


# Using HTML tags inside Jade document
By default, text at the start of a line (or after only white space) represents an HTML tag.
Indented tags are nested, creating the tree like structure of html.

ul
  li Item A
  li Item B
  li Item C

<ul>
  <li>Item A</li>
  <li>Item B</li>
  <li>Item C</li>
</ul>

    => Jade also knows which elements are self closing with the help of DOCTYPE declaration.

img

<img />

    => Block expansion, ( for nesting of HTML elements we generally use Indentation, but their is one more syntax, you can use
           :    to nest one or more HTML elements. ). To save space, jade provides an inline syntax for nested tags.

a: img

<a><img /></a>

    => Self Closing Tags, ( define your own self-closing tag)
Tags such as  img, meta, link and so on are automatically self-closing (unless you use the xml doctype).
You can also explicitly self close a tag by simply a[[ending the  /  character.
Only do this if you know what you are doing.

foo/
foo(bar='baz')/

<foo/>
<foo bar='baz'/>


# Using Attributes with HTML elements
    => Tag attributes look similar to HTML, however their values are just regular JavaScript, means you need a key and put its values inside a
          parenthesis, and If you have multiple attributes than separate them using comma.

a(href='google.com') Google
<a href="google.com">Google</a>

    => All the JavaScript expressions work fine too, You are allowed to write any custom JavaScript code, and that might help you generate custom html.
          use a     -    before the JavaScript expression, so that Jade Compiler treats that line as a JavaScript Expression.

- var authenticated = true
body(class=authenticated ? 'authed' : 'anon')
<body class="authed"></body>

    => If you have many attributes, you can also spread them across many lines, and there is no need to use comma to separate them.
input(
  type="checkbox"
  name="agreement"
  checked
)

    => Unescaped Attributes, ( So, you define a value for attribute and then you want to use that value as it is, tell the Jade Compiler do not worry about this value.)
By default, all attributes are escaped (replacing special characters with escape sequences) to prevent attacks such as cross site scripting.
If you need to use special characters you can use != instead of =

div(escaped="<code>")
<div escaped="&lt;code&gt;"></div>

div(unescaped!="<code>")
<div unescaped="<code>"></div>
// Danger, You must be sure to sanitize any user inputs to avoid Cross Site Scripting

    => Boolean Attributes
Boolean attributes are mirrored by jade, and accept bools, like,  true or false as in JavaScript.
When no value is specified, true is assumed.

input(type='checkbox', checked)
<input type="checkbox" checked="checked">

input(type='checkbox', checked=true)
<input type="checkbox" checked="checked">

input(type='checkbox', checked=false)
<input type="checkbox">

input(type='checkbox', checked=true.toString())
<input type="checkbox" checked="true">

doctype html
<!DOCTYPE html>
input(type='checkbox', checked)
<input type="checkbox" checked>

input(type='checkbox', checked=true)
<input type="checkbox" checked>

input(type='checkbox', checked=false)
<input type="checkbox">

input(type='checkbox', checked=true && 'checked')
<input type="checkbox" checked="checked">

    => Style Attributes
The style attribute can be a string, but it can be an object, which is handy when parts of the style are generated by JavaScript.

a(style="color:red;background:greenl") This is that simple text
<a style="color: red; background: green;">This is that simple text</a>

    => Class Attributes
The  class  attributes can ba a string, but it can be an array of class names, which is handy when generated from Java-script.

- var classes = ['foo', 'bar', 'baz'];
a(class=classes)
<a class="foo bar baz"></a>

a(class=classes class=['bing'])
<a class="bing foo bar biz"></a>

    => Class Literal, ( easy and Simple way to define classes for any HTML element), If no HTML element is used with .class than a DIV is assumed.

a.button
<a class="button"></a>

.content
<div class="content"></div>

    => ID Literal, (simple and easy way to define ID for HTML elements), If no HTML element is used with #ID than DIV is assumed.

a#main-link
<a id="main-link"></a.

#content
<div id="content"></div>

    => &attributes (and attributes) can be used to explode an object into attributes of an element

div#foo(data-bar="foo")&attributes({'data-foo': 'bar'}) Lets talk with me
<div id="foo" data-bar="foo" data-foo="bar">Lets talk with me</div>

Danger: Attributes applied using  &attributes are not automatically escaped, You must be sure to sanatize any user inputs to avoid
Cross Site Scripting. This is done for you if you passing in attributes from a mixin call.


# Case ( Generate HTML based on different cases defined by JavaScript equivalent code)

- var friends = 10;     // This is JavaScript variable
case friends
  when 0
    p You have no friends
  when 1
    p You have a friend
  default
    p You have #{friends} friends

<p>You have 10 friends<p>

    => Case Fall Through
You can use fall through just like in a select statement in JavaScript.

- var friends = 0
case friends
  when 0
  when 1
    p You have very few friends
  default
    p You have #{friends} friends

<p>You have very few friends</a>

    => Block Expansion
Block expansion may also be used

- var friends = 1
case friends
  when 0: p you have no friends
  when 1: p you have a friend
  default: p you have #{friends} friends

<p>You have a friend</a>


# Code and Text Interpolation
Jade makes it possible to write inline JavaScript code in your templates,
There are three types of code,

    => Unbuffered Code
Unbuffered code starts with a  -  does not add any output directly:

- for (var x=0; x < 3; x++)
  li item

<li>item</li>
<li>item</li>
<li>item</li>

    => Buffered Code
Buffered code starts with  =  and output the result of evaluating the JavaScript expression in the template,
For security, it is first HTML escaped:

p
  = 'This code is <escaped>!'

<p>This code is &lt;escaped&gt;!</p>

p
  'This is very Simple'
p
  This is very Simple

-var user = { description: 'foo bar baz'}
-var authorized = false
#user
  if user.description
    h2 Description
    p.description user.description
    p.description= user.description


<div id="user">
  <h2>Description</h2>
  <p class="description">user.description</p>
  <p class="description">foo bar baz</p>
</div>


    => Unescaped Buffered Code
Unescaped buffered code starts with  !=  and output the result of evaluating the JavaScript expression in the template.
It is not safe for user input:

p
  != 'This code is <strong>not<strong> !escaped'

<p>This code is <strong>not<strong> escaped!</p>

    => Interpolation
Both plain-text and piped-text support interpolation.

- var user = {name: 'Hello world!'}
p Welcome #{user.name}

<p>Welcome Hello world!</p>

    => Unescaped Interpolation
You can also use unescaped interpolation in output HTML:

-var user = {name: '<strong>Hello world!<strong>'}
p Welcome #{user.name}
p Welcome !{user.name}

<p>Welcome &lt;strong&gt;Hello world!&lt;/strong&gt;</p>
<p>Welcome <strong>Hello world!</strong></p>


# Conditionals, ( generate HTML code based on if-else statements )
Jade's first-class conditional syntax allows for optional parenthesis, and you may now omit the leading - otherwise it's identical, still just regular javascript:

- var user = { description: 'foo bar baz' }
- var authorised = false
#user
  if user.description
    h2 Description
    p.description= user.description
  else if authorised
    h2 Description
    p.description.
      User has no description,
      why not add one...
  else
    h1 Description
    p.description User has no description

<div id="user">
  <h2>Description</h2>
  <p class="description">foo bar baz</p>
</div>

    => Jade also provides a negated version   unless   (the following are therefore equivalent):

unless user.isAnonymous
  p You're logged in as #{user.name}

if !user.isAnonymous
  p You're logged in as #{user.name}


# Iteration over JavaScript objects using each and while statements

    => each
jade's first-class iteration syntax makes it easier to iterate over arrays and objects within a template:

ul
  // Don't use white-space before = sign
  each val in [1,2,3,4,5]
    li= val

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

    => You can also get the index as you iterate:

ul
  each val, index in ['zero', 'one', 'two']
    li= index + ': ' + val

<ul>
  <li>0: zero</li>
  <li>1: one</li>
  <li>2: two</li>
</ul>

    => Jade also lets you iterate over the keys in an object:

ul
  each val, index in {1: 'one', 2: 'two', 3: 'three'}
    li= index + ': ' + val

    => The object or array to iterate over is just plain JavaScript so it can be a variable or the result of a function call or almost anything:

- var values = []
ul
  each val in values.length ? values: ['There are no values']
    li= val

<ul>
  <li>There are no values</li>
</ul>

    => while
You can also use  while to create a loop

- var n = 0
ul
  while n < 4
    li = n++


# Extends - Template Inheritance ( Using extends and block keyword )
The  extends  keyword allows a template to extend a layout or parent template.
It can then override certain pre-defined blocks of content.

//-FILE:  layout.jade
doctype html
html
  head
    //- So this is a block named title,
    //- you can extend this into another template.
    block title
  body
    //- This block name is content
    block content

//- FILE:  index.jade
extends layout.jade

//- Time to use our pre-defined blocks
block title
  title Simple Node Application

block content
  h1 Welcome to my first Node Application

//- FILE:  index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Node Application</title>
  </head>
  <body>
    <h1>Welcome to my first Node Application</h1>
  </body>
</html>


# Filters
Filters let you use other languages (like, HTML, XML,,,) within a jade template. They take a block of plain text as an input.

//- FILE:  index.jade
:markdown
  # Markdown

  I Often like including markdown documents

script(type="text/coffeescript")
  :coffee
      console.log 'This is coffee script'

//- FILE:  index.html

<h1 id="markdown">Markdown</h1>
<p>I Often like including markdown documents</p>

<script type="text/coffeescript">(function() {
  console.log('This is coffee script');

}).call(this);

</script>


# Includes ( Similar to require()  or  include()  function in PHP Language )
    => Includes allow you to insert the content of one jade file into another.

//- FILE:  index.jade
doctype html
html
  include ./includes/head.jade
  body
    h1 My Site
    p Welcome to my super lame site
    include ./includes/foot.jade

//- FILE:  includes/head.jade
head
  title My Simple Node Application
  script(type="text/javascript", src="js/jquery.min.js")
  script(type="text/javascript", src="js/app.js")

//- FILE:  includes/foot.jade
#footer
  p Copyright 1990-2014 (c) foobar


//- FILE:  index.html  (generated using Jade)
<!DOCTYPE html>
<html>
  <head>
    <title>My Simple Node Application</title>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
  </head>
  <body>
    <h1>Welcome to my Simple website</h1>
    <p>this is cool</p>
    <div id="footer">
      <p>Copyright 1990-2014 (c) foobar</p>
    </div>
  </body>
</html>


    => Including filtered text
You can combine filters with includes to filter things as you include them.

//- FILE:  index.jade
doctype html
html
  head
    title A Simple Article
  body
    include:markdown article.md

//- FILE:  article.md
This is an article written in markdown.
In order to apply the transform markdown you must install one of "marked","supermarked","markdown-js","markdown"

<!DOCTYPE HTML>
<html>
  <head>
    <title> An Article</title>
  </head>
  <body>
    <h1>article.md</h1>
    <p>This is an article written in markdown</p>
  </body>
</html>

//- FILE:  index.html ( generated file using Jade)
<!DOCTYPE html>
<html>
  <head>
    <title>A Simple Article</title>
  </head>
  <body><p>&lt;!DOCTYPE HTML&gt;</p>
<html>
  <head>
    <title> An Article</title>
  </head>
  <body>
    <h1>article.md</h1>
    <p>This is an article written in markdown</p>
  </body>
</html>

  </body>
</html>


# Template Inheritance
Jade supports inheritance via the Keywords  block  and  extends. Jade block can provide default content
    => A block is simply a "block" of jade that may be replaced within a child template. This process is recursive

//- FILE:  layout.jade
html
  head
    title My Site - #{title}
    block scripts
      script(src='/jquery.js')
  body
    block content
    block foot
      #footer
        p some footer content

Now we do not want to use the defaul content of blocks  scripts and content, so lets re-define them.
//- FILE:  page-a.jade
extends ./layout.jade

block scripts
  script(src='/jquery.js')
  script(src='/pets.js')

block content
  h1= title
  each pet in pets
    include pet

This is possible to override a block to provide additional blocks. Here we are extending layout.jade but we are re-defining the content block.
//- FILE:  sub-layout.jade
extends ./layout.jade

block content
  .sidebar
    block sidebar
      p nothing
  .primary
    block primary
      p nothing

//- FILE:  page-b.jade
extends ./sub-layout.jade

block content
  .sidebar
    block sidebar
      p nothing
  .primary
    block primary
      p nothing

    => Block append / prepend
Jade allows you to replace (default), prepend, or append blocks. Suppose for example, you have default scripts in a
"head" block that you wish to utilize on every page and there are also some custom scripts that might be diffrent for a diffrent web pages.

//- FILE:  layout.jade
html
  head
    block head
      link(rel="stylesheet", href="style/bootstrap.min.css")
      script(type="text/javascript", src="js/jquery.js")
      script(type="text/javascript", src="js/bootstrap.min.js")

    body
      block content

Now you are extending this template for your website game/application page, and you need to add some more scripts,
This is why, you don't want to replace the default content of  scripts block, This is where 'append' can help you.

//- FILE:  index.jade
extends layout.jade

block append head
  script(type="text/javascript", src="js/app.js")
  script(type="text/javascript", src="js/game.js")

block content
  h1 Welcome to my game page

//- FILE:  index.html (Generated from index.jade file)

<html>
  <head>
    <link rel="stylesheet" href="style/bootstrap.min.css"/>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
    <script type="text/javascript" src="js/game.js"></script>
    <body>
      <h1>Welcome to my game page</h1>
    </body>
  </head>
</html>


# Mixins  ( Jade function ) ( and two global objects,   attributes  , and   &attributes )
Mixins allow you to create reusable blocks of jade

//- Declaration of a Jade mixins
mixin list
  ul
    li Simple
    li Hello
    li world

// using mixins
+list
+list

<ul>
  <li>Simple</li>
  <li>Hello</li>
  <li>world</li>
</ul>
<ul>
  <li>Simple</li>
  <li>Hello</li>
  <li>world</li>
</ul>

    => Mixins are compiled to functions and can take arguments just like JavaScript functions.

mixin pet(name)
  li.pet= name

ul
  +pet('cat')
  +pet('dog')
  +pet('pig')

<ul>
  <li class="pet">cat</li>
  <li class="pet">dog</li>
  <li class="pet">pig</li>
</ul>

    => Mixin BlocksMixins can also take a block of jade to act as the content

//- FILE:  index.jade
mixin article(title)
  .article
    .article-wrapper
      h1= title
      if block
        block
      else
        p No content provided

+article('Hello world')
+article('Hello World')
  p This is my
  p Amazing article

//- FILE:  index.html ( generated HTML code)
<div class="article">
  <div class="article-wrapper">
    <h1>Hello world</h1>
    <p>No content provided</p>
  </div>
</div>
<div class="article">
  <div class="article-wrapper">
    <h1>Hello world</h1>
    <p>This is my</p>
    <p>Amazing article</p>
  </div>
</div>

    => Mixin Attributes
Mixins also get an implicit attributes argument taken from the attributes passed to the mixin:

mixin link(href, name)
  //- attributes == {class: "btn"}
  a(class!=attributes.class, href=href)= name

+link("/demo.html", "Demo to link")(class="btn")

<a href="/demo.html" class="btn">Demo to link</a>

    => You can also use with  &attributes

mixin link(href,name)
  a(href=href)&attributes(attributes)= name

+link("/demo.html", "demo to link")(class="btn", id="button")

<a href="/demo.html" class="btn" id="button">demo to link</a>

    => Rest Arguments
You can write mixins that take an unknown number of arguments using the 'rest arguments' syntax

mixin list(id, ...items)
  ul(id=id)
    each item in items
      li= item

+list('my-list', 1, 2, 3, 4)

<ul id="my-list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>