native-view-helpers

native view helpers for NodeJS

npm install native-view-helpers
9 downloads in the last week
24 downloads in the last month

Native view helpers for NodeJS

Build Status NPM version

A collection of helper for NodeJS templates.

npm install native-view-helpers

Overview

Usage

Node native helpers use with express

// for static helpers
app.locals.$ = require('native-view-helpers');

// or inside and in examples
var helper = require('native-view-helpers');

Use in templates

EJS templates:

<%- $.nl2br('\r\n') %> // out: <br />
<%- $.ucFirst('message') %> // out: Message
<%- $.date.format('Y/m/d H:i:s') %>
<%- $.html.a('/url-address', 'Label') %>
<%- $.html.charset() %>

> Use form

<%- $.form.begin('/target') %>

<%- $.form.label('Username') %>
<%- $.form.textField('username') %>

<%- $.form.label('Password') %>
<%- $.form.passwordField('password') %>

<%- $.form.submitButton('Login') %>

<%- $.form.end() %>

> Or active form

<% var form = $.activeForm('/target') %>
<%- form.begin() %>

<%- form.label('username') %>
<%- form.textField('username', { placeholder: 'Username'}) %>

<%- form.label('Password') %>
<%- form.passwordField('password', { placeholder: 'Password'}) %>

<%- form.submitButton('Login') %>
<%- form.end() %>

> Use dropDownList

<%- $.form.dropDownList('category', null, ['Category 1', 'Category 2', 'Category 3'], { empty: '-- Select --'}) %>
<%- $.form.dropDownList('category', 'val3', { val1: 'Category 1', val2: 'Category 2', val3: 'Category 3'}) %>
<%- $.form.dropDownList('category', 12, [{ id: 10, name: 'Category 1'}, { id: 12, name: 'Category 2'}], { value: 'id', label: 'name'}) %>

> Use radio button list

// in javascript
var radioButtonList = {
    "value1": "Label 1",
    "value2": "Label 2",
    "value3": "Label 3" 
};

<%- $.form.radioButtonList('name', 'value1', radioButtonList) %>

> radio button list with custom template

<%- $.form.radioButtonList('name', 'value1', radioButtonList, { template: '{input} &lt;span&gt;{label}&lt;/span&gt;' }) %>

> Use pagination

<%- $.widgets.pagination({page: 1, pages: 12 }) %>
<%- $.widgets.pagination({page: 1, count: 120, limit: 10 }) %>
<%- $.widgets.pagination({page: 1, pages: 12, url: '/index?sort=name' }) %> out: /index?sort=name&page=[num]
<%- $.widgets.pagination({page: 1, pages: 12, url: '/index?sort=name', query: 'p' }) %> out: /index?sort=name&p=[num]

> Building tree

var list = [
    { 
        id: 1, 
        name: 'Main Category', 
        children: [ 
            { id: 2, name: 'Sub Category 1' }, 
            { id: 2, name: 'Sub Category 1'    } 
        ]
    }
];

<%- $.widgets.nestedList(list, function (fn, el, lvl) { return fn.html.a('/info/'+ el.id, el.name); }) %>

Go to contents


Helpers API

Basic

e - escape

escape string
e(string)

helper.e('escape this content');

url

url helper
url(url_string)

var url = helper.url('http://example.com/?show=name');
url.setQs('name', 'value'); // set Query string name=value
url.getUrl(); // return http://example.com/?shown=name&name=value

// alternative linked solution
helper.url('http://ex.com/?page=5').setQs('page',10).getUrl();

numberFormat

PHP number format method
numberFormat(number, options)
number_fromat(number, decimals, dec_point, thousands_sep)

helper.numberFormat(10000.11111, { sep: ',', decimals: 2});
// return 10,000.11

// PHP style - snake case version
helper.number_format(10000.1111, 2, '.', ',');
// return 10,000.11

numberFormat(number, options)

Options:

  • sep: thousands separator
  • decpoint: decimal separator
  • decimals: number of decimals

number_format(number, decimals, dec_point, thousands_sep)

mergeObject

Merge to JSON object
mergeObject(toObject, fromObject)

var obj1 = { name: 'Name' };
var obj2 = { age: 25 };
obj1 = helper.mergeObject(obj1, obj2);
// obj1 return: { name: 'Name', age: 25 }

toAttr

Convert JSON object to html key value format.
toAttr(object)

helper.toAttr({ name: "email", value:"mail@mailbox.com" });
// return string: name="email" value="mail@mailbox.com"

repeat

The method repeat the string
repeat(string, count)

helper.repeat('=', 10);
// return: ==========

nl2br

Convert \r\n, \n\r, \r, \n to <br />
nl2br(string)

helper.nl2br('New\nData');
// return: New\n<br />Data

htmlspecialchars

PHP style htmlspecialchars
htmlspecialchars(string, [options])

helper.htmlspecialchars('<a href="link">label</a>', 'ENT_QUOTES');
// return: &lt;a href=&quot;link&quot;&gt;label&lt;/a&gt;

strip_tags

PHP style strip_tags
strip_tags(string, [allowable_tags])

helper.strip_tags('<p><a href="/target">Link</a> Text</p>', '<p>');
// return: <p>Link Text</p>

ucFirst

upper case the first charater
ucFirst(string)

helper.ucFirst('the string ...');
// return: The string ...

countChars

count chars
countChars(RegEx, string)

helper.countChars(/a/g, 'amazone');
// return: 2

Go to contents


HTML

a

Create HTML a element
html.a(link_string, label_string, [options])

helper.html.a('/target', 'Link');
// return: <a hreff="/target">Link</a>

helper.html.a('/target', 'Link', { title: 'Link', class: 'cls' });
// return: <a hreff="/target" title="Link" class="cls">Link</a>

beginEl

Create only open tag with parameters
html.beginEl(name_of_element, options)

helper.html.beginEl('p', { class: 'content'});
// return: <p class="content">

endEl

Create element only close tag
html.endEl(name_of_element)

helper.html.endEl('p');
// return: </p>

el

Create element with close tag
html.el(name_of_element, options)

helper.html.el('p', { class: 'content', html: 'The text'});
// return: <p class="content">The text</p>

charset

Create meta element for charset
html.charset(charset_string [default: 'uft8'])

helper.html.charset();
// return: <meta charset="utf8" />

helper.html.charset('other');
// return: <meta charset="other" />

css

Create link element for style
html.css(url_string, options)

helper.html.css('style.css');
// return: <link href="style.css" rel="stylesheet" type="text/css" media="all" />

helper.html.css('style.css', { media: 'print'});
// return: <link href="style.css" rel="stylesheet" type="text/css" media="print" />

script

Create script source element
html.script(source_string, options)

helper.html.script('app.js');
// return: <script src="app.js" type="text/javascript"></script>

img

Create img element
html.img(image_path, alt, options)

helper.html.img('pic.png');
// return: <img src="pic.png" />

helper.html.img('pic.png', 'Big moon');
// return: <img src="pic.png" alt="big moon" />

helper.html.img('pic.png', 'Big moon', { width: 320 });
// return: <img src="pic.png" alt="big moon" width="320" />

imgText

Create image element with remote url text caption
helper.html.imgText(message, options)

helper.html.imgText('No Image');
// return: <img src="http://www.placehold.it/291x170/EFEFEF/AAAAAA&text=No Image"  />

helper.html.imgText('No Image', { w: 320, h: 240});
// return: <img src="http://www.placehold.it/320x240/EFEFEF/AAAAAA&text=No Image"  />

refresh

Create meta element for refresh
html.refresh(url, time_in_secounds_after_redirect, options)

helper.refresh('http://target.com');
// return: <meta http-equiv="5,http://target.com" />

Go to contents


Date

time

Create unix timestamp
date.time([new Date Or '2013-08-28 19:45 ])

helper.date.time(); // retun timestamp in seconds
// return 1377715631

helper.date.time('2013-08-28 19:45');
// return 1377737100

helper.date.time(new Date()); 
// return 1377715631

format

PHP style date format
date.format(format_string, [date_or_timestamp])

helper.date.format('m/d/Y H:i:s', new Date());
// return 08/28/2013 19:45

helper.date.format('m/d/Y H:i:s', 1377737100);
// return 08/28/2013 19:45 

helper.date.format('m/d/Y H:i:s');
// return 08/28/2013 19:45

parse

PHP style date parse
date.format(date_string)
return object: { year, month, day, hour, minute, second, fraction, is_localtime }

php date format options

Go to contents


Form

begin

Create <form> element
form.begin(target_url, options)

helper.form.begin();
// return: <form action="" method="POST">

helper.form.begin(null, { method: 'GET' })
// return: <form action="" method="GET">

helper.form.begin('/target', { upload: true, class: 'form' });
// return: <form action="/target" class="form" method="POST" enctype="multipart/form-data">

form begin options
method: form method, default: POST
upload: set true for file upload, default: false
htmlElementName: use object key for other html attribute. id, class

end

Crate </form> element
form.end()

label

Create <label> element
form.label(shown_label, html_options)

helper.form.label('Username');
// return <label>Username</label>

helper.form.label('Username', { for: 'username' });
// return <label for="username">Username</label>

inputField

Create input field
form.inputField(html_options)
default type text

hiddenField

Create hidden input field
form.hiddenField(name, value, html_options)

textField

Create text type input field.
form.textField(name, value, html_options)

helper.form.textField('username', null, { palceholder: 'Username', class: 'input' });

passwordField

Create password type input field
form.passwordField(name, value, html_options)

fileField

Create field for file upload
form.fileField(name, html_options)

textArea

Create textarea
form.textArea(name, value, html_options)

Create select element
form.dropDownList(name, value, array_json, html_options)

var list = ["Label 1", "Label 2", "Label 3"]; // index value
helper.form.dropDownList('name', null, list);
helper.form.dropDownList('name', 1, list); // selected 2nd

// with empty chooser
helper.form.dropDownList('name', null, list, { empty: '-- Select --'});

// drop down from JSON
var list = { "val1": "Label 1", "val2": "Label 2", "val3": "Label 3" };
helper.form.dropDownList('name', 'val2', list);

// JSON based Array
var list = [
    { "id": 1, "name": "Label 1" },
    { "id": 2, "name": "Label 2" },
    { "id": 3, "name": "Label 3" }
];

helper.form.dropDownList('name', 2, list, { value: "id", label: "name"});

html_options
value: select value from Object
label: select label from Object
empty: empty label

checkBox

Create checkbox type input field
form.checkBox(name, checked, html_options)

radioButton

Create radio button
form.radioButton(name, value, html_options)

radioButtonList

Create radio button list
form.radioButtonList(name, value, list, html_options)

var list = {
    'value1': 'Label 1',
    'value2': 'Label 2',
    'value3': 'Label 3'
};

helper.form.radioButtonList('name', null, list );

helper.form.radioButtonList('name', 'value2', list ); // selected value2

// custom template
helper.form.radioButtonList('name', 'value2', list, { template: '{input}<br>{label}' } ); // selected value2

button

Create button element
form.button(label, html_options)

resetButton

Create reset type input
form.resetButton(label, html_options)

submitButton

Create submit type input
form.submitButton(label, html_options)

Go to contents


ActiveForm

Go to contents


Widgets

pagination

Generate client side pagination
widgets.pagination(options)

helper.widgets.pagination({ page: 1, pages: 10});
// generate: ul -> li -> a elements
// ...
// <li><a href="?page=[page number]">[page number]</a></li>
// ...

// options page and pages with limit
helper.widgets.pagination({ page: 1, pages: 10, limit: 5 });
// from count
helper.widgets.pagination({ page: 1, count: 105, limit: 10 });
// custom url
helper.widgets.pagination({ page: 1, pages: 10, url: '/site'});
// /site?page=[num]
helper.widgets.pagination({ page: 1, pages: 10, url: '/site?name=data'});
// /site?name=date&page=[num]
helper.widgets.pagination({ page: 1, pages: 10, url: '/site', query: 'p'});
// /stie?p=[num]

// with custom range
helper.widgets.pagination({ page: 1, pages: 10, range: 10 });

pagination options
page: current page, default: 1
pages: number of pages
limit: number of pages per side, default: 10
count: number of elements
range: number of shown links, default: 6
url: site url and query elements
query: page query variable name, default: page
active: active link class, default: active
class: ul element class, default: empty

nestedList

Create <ul>,<li> based hierarchical list.
widgets.nestedList(List, callback, params)

var list = [{ 
    "id": 1, 
    "name": "Main Category", 
    "children": [ 
        { "id": 2, "name": "Sub Category 1" }, 
        { "id": 2, "name": "Sub Category 1"    } 
    ] 
}];

helper.widgets.nestedList(list, function (fn, el, lvl) { return el.name; })

callback(helperFunctions, element, level)
nestedList options
ulClass: ul element class, recursive
liClass: li element class, recursive

shippingChooser

Create drop down date list for deliver
widgets.shippingChooser(name_of_select, options)

helper.widgets.shippingChooser('deliver');
// generate drop down list

helper.widgets.shippingChooser('deliver', { date: new Date('2013-08-28') } );
// generate drop down list from 08/28/2013

shipping chooser options
date: instance of Date, from calulate. Default: Now
lang: language, values: en, hu, default: en
sunDay: shown list sun day, default: false

Go to contents


Changelog

Aug 28, 2013 - version: 0.1.3

  • added form.radioButtonList
  • fixed form.checkBox
  • added form tests
  • updated README.md API description

Aug 27, 2013 - version: 0.1.2

  • fix console.log
  • enhacement activeForm dropDownList

Aug 22, 2013 - version: 0.1.1

  • fixed widgets test issue

Aug 22, 2013 - version: 0.1.0

  • added defaults
  • added date plugin
  • added html plugin
  • added form plugin
  • added active form plugin
  • added widgets
  • added tests

Missing, Todo

  • API documentation
  • activeForm tests
  • more template engine example
  • examples

Go to contents


Authors and contributors

Go to contents


License

The MIT License (MIT)

Copyright (c) 2013 Janez

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

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

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

Go to contents


npm loves you