Exemplo n.º 1
0
module.exports = (function () {
  var Handlebars = require('express-hbs');

  var compare = Handlebars.registerHelper('compare', function(v1, v2, options) {
    return _.isEqual(v1, v2)? options.fn(this) : options.inverse(this);
  });

  var startCase = Handlebars.registerHelper('startCase', function(str) {
    return _.startCase(str);
  });

  var toDate = Handlebars.registerHelper('toDate', function(milliSecs) {
    return _.milliSecsToDate(milliSecs);
  });

  var capitalize = Handlebars.registerHelper('capitalize', function(str) {
    return _.capitalize(str);
  });

  var rmCents = Handlebars.registerHelper('rmCents', function(str) {
    return Number(str).toFixed(0);
  });

  return {
    capitalize: capitalize,
    startCase: startCase,
    rmCents: rmCents,
    compare: compare,
    toDate: toDate
  };

})();
Exemplo n.º 2
0
module.exports = function(){  
    hbs.registerHelper('cond', function (v1, operator, v2, options) {
        switch (operator) {
            case '==':
                return (v1 == v2) ? options.fn(this) : options.inverse(this);
            case '===':
                return (v1 === v2) ? options.fn(this) : options.inverse(this);
            case '<':
                return (v1 < v2) ? options.fn(this) : options.inverse(this);
            case '<=':
                return (v1 <= v2) ? options.fn(this) : options.inverse(this);
               case '>':
                return (v1 > v2) ? options.fn(this) : options.inverse(this);
               case '>=':
                return (v1 >= v2) ? options.fn(this) : options.inverse(this);
            case '&&':
                return (v1 && v2) ? options.fn(this) : options.inverse(this);
            case '||':
                return (v1 || v2) ? options.fn(this) : options.inverse(this);
            default:
                return options.inverse(this);
        }
    });
    hbs.registerHelper('latestFeature', function (posts, options) {
        for (id in posts) {
            post = posts[id]
            if (post.featured == true) {
                return options.fn(post);
            }
        };
    });
    hbs.registerHelper('latestPost', function (posts, options) {
        console.log(posts);
        counter = 0;
        latestPost = [];
        for (id in posts) {
            latestPost.push(posts[id])
            counter = counter + 1;
            if (counter > 4) return options.fn(post);
        };
    });
    hbs.registerHelper('moreFeature', function (posts, options) {
        counter = 0;
        featured_post = [];
        for (id in posts) {
            if (counter > 4) break;
            if (posts[id].featured == true) {
                if (counter == 0) {
                    counter = counter + 1;
                    continue;
                }
                counter = counter + 1;
                featured_post.push(posts[id]);
            };
        };
        return options.fn(featured_post);
    });
};
module.exports = function() {

	hbs.registerHelper('preview', function (options) {
		var length = this.html.indexOf('<!-- more -->');
		console.log(this.html.substring(0, length));
		return new hbs.handlebars.SafeString(
			this.html.substring(0, length)
		);
	});

};
Exemplo n.º 4
0
module.exports = function() {
	hbs.registerHelper('convert_images', require('./convert-images'));
	hbs.registerHelper('to_first_paragraph', require('./to-first-paragraph'));
	hbs.registerHelper('read_time', require('./read-time'));
	hbs.registerHelper('inline_css', require('./inline-css'));
	hbs.registerHelper('env', require('./env'));
	hbs.registerHelper('production', require('./production'));
};
Exemplo n.º 5
0
    templateConfig: function(app) {

        app.engine('hbs', hbs.express3({
          partialsDir: config.ROOT + '/app/views/partials',
          layoutsDir: config.ROOT + '/app/views/layouts'
        }));
        
        //helpers
        hbs.registerHelper('isActive', function(item, current){
            return (item === current) ? 'is-active' : '';
        });

        hbs.registerHelper('index', function(index){
            return index+1;
        });

        app.set('view engine', 'hbs');
        
        app.set('views', config.ROOT + '/app/views');        

        //if (config.NODE_ENV === "dev") {
            app.use(express.static(config.ROOT + '/assets'));
        //}
    },
Exemplo n.º 6
0
module.exports = function(){
    hbs.registerHelper('cond', function (v1, operator, v2, options) {
        switch (operator) {
            case '==':
                return (v1 == v2) ? options.fn(this) : options.inverse(this);
            case '===':
                return (v1 === v2) ? options.fn(this) : options.inverse(this);
            case '<':
                return (v1 < v2) ? options.fn(this) : options.inverse(this);
            case '<=':
                return (v1 <= v2) ? options.fn(this) : options.inverse(this);
               case '>':
                return (v1 > v2) ? options.fn(this) : options.inverse(this);
               case '>=':
                return (v1 >= v2) ? options.fn(this) : options.inverse(this);
            case '&&':
                return (v1 && v2) ? options.fn(this) : options.inverse(this);
            case '||':
                return (v1 || v2) ? options.fn(this) : options.inverse(this);
            default:
                return options.inverse(this);
        }
    });
};
Exemplo n.º 7
0
            return done(null, user)
        })
    }
))

// Configure Express
app.set('port', process.env.PORT || 3000)
app.set('dirname', __dirname + '/build')
if (process.env.DEV === 'true') {
    app.set('dirname', __dirname)
}

// Configure templating
var root_url = process.env.ROOT_URL || '/'
hbs.registerHelper('root_url', function () {
    return root_url
})
app.engine('hbs', hbs.express3())
app.set('view engine', 'hbs')
app.set('views', app.get('dirname') + '/views')

// Needed to parse JSON data sent by Backbone
app.use(express.bodyParser())

// For passport authentication
app.use(express.cookieParser())
app.use(express.methodOverride())
app.use(express.session({secret: 'RANDOMSTRING'}))
app.use(passport.initialize())
app.use(passport.session())
Exemplo n.º 8
0
// Register a handlebars helper for themes
function registerThemeHelper(name, fn) {
    hbs.registerHelper(name, fn);
}
Exemplo n.º 9
0
 registerHelper: function(name, fn) {
     exphbs.registerHelper(name, fn);
 },
Exemplo n.º 10
0

app.use(require("cookie-parser")());
app.use(session({ secret: 'casduichasidbnuwezrfinasdcvjkadfhsuilfuzihfioda', resave: false, saveUninitialized: true}));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(require("method-override")(function(req, res){
    if (req.body && typeof req.body === 'object' && '_method' in req.body) {
        var method = req.body._method;
        delete req.body._method;
        return method;
    }
}));

app.use("/", require('./routes/indexRoutes.js'));
app.use("/orders", require('./routes/orderRoutes.js'));

app.use(express.static(__dirname + '/public'))


http.createServer(app).listen(3000);
console.log("server started at http://localhost:3000/");

hbs.registerHelper('if_eq', function(a, b, opts) {
    if(a == b) // Or === depending on your needs
        return opts.fn(this);
    else
        return opts.inverse(this);
});
Exemplo n.º 11
0
global.formatLength = function(l) {
    var hours = parseInt(l/3600);
    var minutes = parseInt((l%3600)/60);
    var seconds = (l%3600)%60;

    if (hours < 10) { hours = "0" + hours; }
    if (minutes < 10) { minutes = "0" + minutes; }
    if (seconds < 10) { seconds = "0" + seconds; }


    return hours + ":" + minutes + ":" + seconds;
}

var app = express();

hbs.registerHelper('_length', global.formatLength);

app.configure(function() {
    app.set('port', process.env.PORT || 3000);

    app.set('view engine', 'hbs');
    app.engine('hbs', hbs.express3({
        partialsDir: __dirname + '/views/partials',
        defaultLayout: __dirname + '/views/layout.hbs'
    }));
    app.set('views', __dirname + '/views');

    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
Exemplo n.º 12
0
app.engine('hbs', exphbs.express4({
    partialsDir: path.join(__dirname, 'views/partials'),
    layoutsDir: path.join(__dirname, 'views/layouts'),
    defaultLayout: 'views/layouts/main.hbs',
}));
app.set('views', path.join(__dirname, 'views'));
app.set("view engine", "hbs");

app.locals.clientId = secrets.clientId;
app.locals.callbackURL = secrets.callbackURL;

exphbs.registerHelper('equal', function(lvalue, rvalue, options) {
    if (arguments.length < 3)
        throw new Error("Handlebars Helper equal needs 2 parameters");
    if( lvalue!=rvalue ) {
        return options.inverse(this);
    } else {
        return options.fn(this);
    }
});

exphbs.registerHelper('add', function(lvalue, rvalue, options) {
    if (arguments.length < 3)
        throw new Error("Handlebars Helper equal needs 2 parameters");
   return parseInt(lvalue) + parseInt(rvalue) ;
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.raw());
Exemplo n.º 13
0
app.use(express.favicon());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);

var fiveDays = 5*86400000;

app.use(express.static(path.join(__dirname, 'public'), { maxAge: fiveDays } ) );

//register a helper for date formatting using handlebars
hbs.registerHelper("formatDate", function(datetime, format) {
  if (moment) {
    f = "ddd DD MMM YYYY HH:mm"
    return moment(datetime).format(f);
  }
  else {
    return datetime;
  }
});

//helper to get the icon for a item type
hbs.registerHelper("getIconForType", function(type) {
	return bc.getIconForType(type);
});

//helper to get the number of data elements
hbs.registerHelper('count', function(type) {
	switch (type) {
		case 'companies':
			return companies.length;
Exemplo n.º 14
0
// all things templating
var hbs = require('express-hbs');

// routing
var routes = require('./routes');

// misc extra stuff you gotta have
var http = require('http');
var path = require('path');

// create the app
var app = express();

hbs.registerHelper('setPageType', function(pageType) {
  this.pageType = pageType;
});

var randomStrings = {
  homePageSubcaption: [
    '...to the jankiest blog on earth',
    '...to the lair of the elusive Tom ForNow',
    '...to the <em>incredible, edible egg!</em>'
    ],
  postsIndexSubcation: [
    'the jankiest blog on earth',
    'the lair of the elusive Tom ForNow',
    'BITCHEZ!!',
    'all hat, no cattle!'
  ]
};
 (function (key) {
   hbs.registerHelper(key, function (context, options) {
     return include(map[key], context, options);
   });
 })(m);
 * Alias for the SafeString method.
 */
function safeString(string) {
  return new hbs.handlebars.SafeString(string);
}


// --------------------------
// Handlebars helpers.
// --------------------------

/**
 * JSON Stringify helper.
 */
hbs.registerHelper('json', function (context) {
  return safeString(JSON.stringify(context));
});

/**
 * Configuration exporter.
 */
hbs.registerHelper('config', function (context) {

  // Safely parse context.
  var config = this;

  // Guard blog settings, if available.
  if (context && context.data && context.data.blog) {
    config.blog = context.data.blog;
  }
Exemplo n.º 17
0
global.appRoot = path.resolve(__dirname)
require('./routes/watcher')

/**
 * A simple if condtional helper for handlebars
 *
 * Usage:
 *   {{#ifvalue env value='development'}}
 *     do something marvellous
 *   {{/ifvalue}}
 * For more information, check out this gist: https://gist.github.com/pheuter/3515945
 */
hbs.registerHelper('ifvalue', function (conditional, options) {
  if (options.hash.value === conditional) {
    return options.fn(this)
  } else {
    return options.inverse(this)
  }
})

hbs.registerHelper('formatDate', function (date) {
  // This guard is needed to support Blog Posts without date
  // the takeway point is that custom helpers parameters must be present on the context used to render the templates
  // or JS error will be launched
  if (typeof (date) == 'undefined') {
    return 'Unknown'
  }

  var _date = new Date(date)
    // These methods need to return a String
  return _date.getUTCMonth() + '/' + _date.getFullYear()
Exemplo n.º 18
0
  deferred = Q.defer();
  var req = client.get(url, function(data) {
          deferred.resolve(data);
        }
      );

  req.on('error', function(err){
      deferred.reject(err);
  });
  return deferred.promise;
}



Handlebars.registerHelper("projection", function(context, options) {

  return context.posts.title;
});

Handlebars.registerHelper("context", function(context, options) {

  // Building url
  var appOtions = settings.constants,
      url = appOtions.SERVICES_PATH + ":" + appOtions.SERVICES_PORT + "/" + context;
  for(key in options.hash) {
    if(options.hash.hasOwnProperty("id") && key === "id") {
      url = url + "/" + options.hash["id"];
    }
  }

  /*var responseData = {
        "posts": {
Exemplo n.º 19
0
exports.attach = function (options) {
  var app = this;
  var crypto = require('crypto');
  var express = require('express');
  var hbs = require('express-hbs');
  var RSS = require('rss');
  var validator = require('validator');

  hbs.registerHelper('selected', function(current, selected) {
    return (current == selected) ? 'selected' : '';
  });

  app.server = express();

  app.server.engine('hbs', hbs.express3({
    partialsDir: app.dir + '/views/partials'
  }));

  app.server.locals({
    conf: app.conf,
  });

  app.server.set('view engine', 'hbs');
  app.server.set('views', app.dir + '/views');
  app.server.use(express.static(app.dir + '/public'));
  app.server.use(express.bodyParser());

  app.server.get('/', function(req, res) {
    res.render('index', {
      feed: app.defaultSample,
      samples: app.samples,
      samplesJSON: JSON.stringify(app.samples),
      defaultSampleKey: app.defaultSampleKey,
    });
  });

  app.server.get('/edit/:private_id', function(req, res) {
    app.feed.findOne({private_id: req.params.private_id}, function(err, feed) {
      if (feed) {
        res.render('edit', {
          feed: feed,
          samples: app.samples,
          samplesJSON: JSON.stringify(app.samples),
          defaultSampleKey: 'new',
        });
      }
      else {
        res.send(404);
      }
    });
  });

  app.server.get('/preview', function(req, res) {
    app.parse(req.query, function(err, items) {
      res.render('preview', {items: items});
    });
  });

  app.server.post('/publish', function(req, res) {
    var errors = [];
    var isNewFeed = req.body.private_id ? false : true;

    if (!validator.isURL(req.body.url)) errors.push('URL is not valid.');
    if (!validator.isEmail(req.body.email)) errors.push('E-mail is not valid.');
    if (!validator.isLength(req.body.title, 1)) errors.push('Title is not defined.');
    if (!validator.isLength(req.body.item_selector, 1)) errors.push('Item selector not defined.');
    if (!validator.isLength(req.body.target_selector, 1)) errors.push('Target selector not defined.');
    if (!validator.isLength(req.body.title_selector, 1)) errors.push('Title selector not defined.');

    if (!errors.length) {
      if (isNewFeed) {
        req.body.private_id = crypto.randomBytes(8).toString('hex');
        req.body.public_id = crypto.randomBytes(8).toString('hex');
      }

      app.feed.findOneAndUpdate({private_id: req.body.private_id}, req.body, {upsert: true}, function(err, doc) {
        if (err) {
          app.err(err);
          res.render('modal_content', {status: false, title: 'Error', errors: ['Feed could not be saved.']});
        }
        else {
          app.mail({to: doc.email, subject: 'Feed "' + doc.title + '" created'}, 'feed_published', doc);
          res.json({'location': 'http://95.85.20.120/edit/' + doc.private_id});
        }
      });
    }
    else {
      res.render('modal_content', {status: false, title: 'Feed could not be saved', errors: errors});
    }
  });

  app.server.get('/rss/:public_id', function(req, res) {
    app.feed.findOne({public_id: req.params.public_id}, function(err, feed) {
      if (feed) {
        var rss = new RSS({
          title: feed.title,
          feed_url: 'http://pagetty.com/rss/' + feed.public_id,
          site_url: feed.url,
          author: feed.email,
        });

        app.parse(feed, function(err, items) {
          for (var i in items) {
            var item = items[i];

            if (item.title && item.target) {

              if (item.image && !item.content) {
                item.content = '<p><img src="' + item.image + '" /></p>';
              }

              rss.item({
                url: item.target,
                title: item.title,
                description: item.content,
                author: item.author,
              });
            }
          }

          res.send(rss.xml());
        });
      }
      else {
        res.send(404);
      }
    });
  });

  app.server.get('/terms', function(req, res) {
    res.render('terms');
  });

}
Exemplo n.º 20
0
registerHelper = function (){
  hbs.registerHelper("isLocal", function(url) {
    return url === config.development.url
  });
}
Exemplo n.º 21
0
// Declare any Express [middleware](http://expressjs.com/api.html#middleware) you'd like to use here
// Log requests, using an appropriate formatter by env
app.use(morgan(devEnv ? 'dev' : 'combined'));
// Include request parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
// Gzip responses when appropriate
app.use(compression());
// Enable the ACE global middleware (populates res.locals with add-on related stuff)
app.use(addon.middleware());
// Enable static resource fingerprinting for far future expires caching in production
app.use(expiry(app, {dir: staticDir, debug: devEnv}));
// Add an hbs helper to fingerprint static resource urls
hbs.registerHelper('furl', function(url){ return app.locals.furl(url); });
// Mount the static resource dir
app.use(express.static(staticDir));

// Show nicer errors when in dev mode
if (devEnv) app.use(errorHandler());

// Wire up your routes using the express and `atlassian-connect-express` objects
routes(app, addon);
// require('ace-abotars')(addon, app);

// Boot the damn thing
http.createServer(app).listen(port, function(){
  console.log()
  console.log('Add-on server running at '+ (addon.config.localBaseUrl()||('http://' + (os.hostname()) + ':' + port)));
  // Enables auto registration/de-registration of add-ons into a host in dev mode
Exemplo n.º 22
0
    bodyParser      = require('body-parser'),
    compress        = require('compression'),
    favicon         = require('static-favicon'),
    methodOverride  = require('method-override'),
    errorHandler    = require('errorhandler'),
    config          = require('./config'),
    environment     = require('./config/environment')(),
    routes          = require('./routes'),
    secrets         = require('./config/secrets');

var app = express();

hbs.registerHelper('ifvalue', function (conditional, options) {
  if (options.hash.value === conditional) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

app.set('env', environment);
app.set('port', config.server.port);
app.engine('hbs', hbs.express3());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.set('sessions dir', './tmp/sessions');

//////////////////////////////////////////////////

function LoggingRedisStore(options) {
  var self = new RedisStore(options);
Exemplo n.º 23
0
Ghost.prototype.registerThemeHelper = function (name, fn) {
    hbs.registerHelper(name, fn);
};
Exemplo n.º 24
0
// Start fake DOM to allow the usage of jQuery server-side.
jsdomEnv('<html><head></head><body></body></html>', function (err, window) {
  jQuery = jQuery(window);
});


// --------------------------
// Handlebars helpers.
// --------------------------

/*
 * JSON Stringify helper.
 */
hbs.registerHelper('json', function (context) {
  return JSON.stringify(context);
});

hbs.registerHelper('abstract', function (context) {

  // Get a user defined abstract if available.
  if (this.abstractText) return this.abstractText;

  var $html = jQuery(this.html),
      result = '',
      min = 240,
      max = 500;

  console.log(this.featuredMedia);

  $html.filter('p').each(function(index) {
Exemplo n.º 25
0
module.exports = function(app, config) {
	app.locals.title = 'Guide App';
	app.locals.prod_env = 'prod' === config.env;
	app.locals.static_path = config.static_path;

	app.engine('hbs', hbs.express3({
	  	partialsDir: path.join(config.root, 'views', 'partials'),
	  	layoutsDir: path.join(config.root, 'views', 'layout'),
	}));

	app.set('view engine', 'hbs');
	app.set('views', path.join(config.root, 'views'));

	// Register view helper
	hbs.registerHelper('join', function(list, separator) {
		return new hbs.SafeString(list.join(separator));
	});

	hbs.registerHelper('toString', function(object){
		return JSON.stringify(object);
	});

	app.set('view cache', false);
  	app.use(favicon());
  	app.use(bodyParser.json());
	app.use(bodyParser.urlencoded());
	app.use(cookieParser(config.salt));
	app.use(session({ 
		store: new RedisStore({
			host: config.redis.host,
			port: config.redis.port
		}), 
		secret: config.secret,
		cookie : {
            maxAge: 1000*60*60*24*1000
        } 
    }));

    app.use(flash());
	app.use(logger('dev'));
  	app.use(express.static(path.join(config.root, 'public')));

	app.use(function(req, res, next) {
	    res.removeHeader("X-Powered-By");
	    next();
  	});

  	app.use(function(req, res, next){
  		app.locals.flash = {
  			flash_error: req.flash('error'),
  			flash_info: req.flash('info'),
  			flash_success: req.flash('success'),
  			flash_warning: req.flash('warning')
  		};

  		next();
  	});

  	if(app.get('env') === 'dev') {
	  	app.use(express.errorHandler());
  	}
};
Exemplo n.º 26
0
var registerHelper = function () {

  //
  // ### Table of Contents helper
  //
  // @param  {Object} options object,
  // start is the starting level and
  // end the max depth of the headline level
  //
  // *Usage example:*
  // `{{toc}}`
  // `{{toc start="1" end="3"}}`
  //
  // Defaults to start="1"
  // Defaults to end="4"
  //
  // **returns** SafeString content html.
  //
  hbs.registerHelper('toc', function(options) {

    options = options || {};
    options.hash = options.hash || {};

    var toc = [];
    var $ = cheerio.load(this.html);
    var startLevel = options.hash.start || 1;
    var maxDepth = options.hash.end || 4;

    var idPrefix = 'toc_';
    var idIncrement = 1;

    var isIdFormat = function(content){
      var english = /^[A-Za-z0-9_]*$/;  // only a-zA-Z0-9_ will be used for the value of id attribute
      if (english.test(content)) {
        return true;
      }else{
        return false;
      }
    };

    /*
    * TODO: Need to find a way to alter DOM element in hbs helpers
    */
    var getHeadlines = function(start, end, current, elem) {
      if(parseInt(current) > parseInt(end)) { return; }
      if(_.isUndefined(current)) {
        $('h' + start).each(function(i, elem) {
          var headerElem = $(elem);
          if(!isIdFormat(headerElem.text())) { // when id not equal title
            var newId = idIncrement++;
            $(elem).attr('id', idPrefix + newId);
          }
          toc.push('<li><a href="#' + $(elem).attr('id') + '">' + $(elem).text() + '</a></li>');
          getHeadlines(start, end, parseInt(start) + 1, elem);
        });
      } else {
        var $subHeaders = $(elem).nextUntil('h' + (parseInt(current) - 1), 'h' + current);
        if($subHeaders.length !== 0) {
          toc.push('<ul>');
          $subHeaders.each(function(i, elem) {
            toc.push('<li><a href="#' + $(elem).attr('id') + '">' + $(elem).text() + '</a></li>');
            getHeadlines(start, end, parseInt(current) + 1, elem);
          });
          toc.push('</ul>');
        }
      }
    };

    // Ignore the cases where no header with startLevel exists
    while(startLevel <= maxDepth && $('h' + startLevel).length === 0){
      startLevel++;
    }
    if (startLevel <= maxDepth) {
      getHeadlines(startLevel, maxDepth);
    }

    return new hbs.handlebars.SafeString(toc.join(' '));

  });
};
Exemplo n.º 27
0
		numeral = require('numeral');


// ===============================================
// Setup handlebars and SASS
// ===============================================

	handlebars.registerHelper('formatNumber', function(meters, format, scale, isMetric) {
		
		var factor, distance;
		
		// Switch based on scale and system
		if (scale === 'big') {
			units = (isMetric) ? 'km' : 'mi';
			distance = (isMetric) ? meters/1000 : ((meters/1000) * 0.6214);
		} else {
			units = (isMetric) ? 'm' : 'ft';
			distance = (isMetric) ? meters : (meters * 3.28084);
		}
		
		// Format it
		return numeral(distance).format(format) + units;
		
	});
	
	app.engine('hbs', handlebars.express3({
		partialsDir: __dirname + '/views/partials',
		layoutsDir: __dirname + '/views/layouts',
		defaultLayout: __dirname + '/views/layouts/default.hbs'
	}));
Exemplo n.º 28
0
'use strict';
var hbs = require('express-hbs');
var features = require('./features');
var moment = require('moment');
var path = require('path');
var config = require('./config');

// hbs.registerPartials(path.resolve(__dirname + '/../views/partials'));

if (config.env !== 'production') {
  var hbsutils = require('hbs-utils')(hbs);
  hbsutils.registerWatchedPartials(path.resolve(__dirname + '/../views/partials'));
}

hbs.registerHelper('bust', function () {
  return (Math.random() * 1e5 | 0).toString(16);
});

hbs.registerHelper('feature', function(request, flag, options) {
  if (features(flag, request)) {
    return options.fn(this);
  } else if (options.inverse) {
    return options.inverse(this);
  }
});

hbs.registerHelper('eachkey', function eachKey(object) {
  var options = arguments[arguments.length - 1];
  var ret = '';
  for (var key in object) {
    if (object.hasOwnProperty(key)) {
Exemplo n.º 29
0
app.engine('hbs', hbs.express3({
  partialsDir: __dirname + '/views/partials'
}));


// Make our db accessible to our resume
app.use(function(req,res,next){
    req.db = db;
    next();
});


var colors = {};

hbs.registerHelper('color', function() {

  return 'the ' + this + ' is ' + colors[this];
});

app.get('/', function(req, res){

  colors = {
    turtle  : 'green',
    giraffe : 'yellow',
    flamingo: 'pink'
  };
  
  var data = {animals:['flamingo','turtle','giraffe']}
    console.log("Hello "+data)
  res.render('index', data);
});
Exemplo n.º 30
0
'use strict';

var hbs = require('express-hbs');

hbs.registerHelper('log', function(object, options) {

  console.log(object);

  return new hbs.SafeString("");
});

exports = module.exports = function(app, express) {
    // Handlebars template for rendering html
    app.engine('hbs', hbs.express3({
        extname: ".html",
        partialsDir: __dirname + '/src/partials/api'
    }));
    app.set('view engine', 'hbs');
    app.set('views', __dirname + '/src/partials/api');

    // Configuration for server
	app.configure(function() {
	    app.use(express.cookieParser());
	    app.use(express.bodyParser());
	    app.use(express.json());
	    app.use(express.urlencoded());
	    app.use(express.methodOverride());
	    app.use(express.favicon());
	    app.use(express.session({
	        secret: 'abc12345',
	        cookie: {