コード例 #1
0
ファイル: gulpfile.js プロジェクト: mavieth/chug
  nunjucks = require('nunjucks');
  path = require('path'),
  rename = require('gulp-rename'),
  sass = require('gulp-sass'),
  through = require('through2'),
  url = require('url'),
  concat = require('gulp-concat'),
  minify = require('gulp-minify-css');

var bourbon = require('node-bourbon').includePaths,
  neat = require('node-neat').includePaths;

var site = require('./config.json');

var env = nunjucks.configure(['src', 'src/partials/', 'src/pages'], {
  noCache: true
});

var mdOptions = {
  html: true
};

var postNamePattern = /(\d{4})-(\d{1,2})-(\d{1,2})-(.*)/;

gulp.task('index', ['posts'], function() {
  gulp.src('src/index.html')
    .pipe(data(site))
    .pipe(nunjucksRender())
    .pipe(gulp.dest('dist'));
});
コード例 #2
0
ファイル: server.js プロジェクト: BarnabyBishop/arch
	browserify = require('browserify-middleware'),
	reactify = require('reactify'),
	less = require('less-middleware'),
	nunjucks = require('nunjucks'),
	config = require('./client/config'),
	routes = require('./server/routes'),
	path = require('path');

// initialise express
var app = express();

// use nunjucks to process view templates in express
app.set('views', path.join(__dirname, 'server/templates/views'))
app.set('view engine', 'html')
nunjucks.configure('server/templates/views', {
	autoescape: false,
    express: app
});

// less will automatically compile matching requests for .css files
app.use(less('public'));
// public assets are served before any dynamic requests
app.use(express.static('public'));

// common packages are precompiled on server start and cached
app.get('/js/' + config.common.bundle, browserify(config.common.packages, {
	cache: true,
	precompile: true
}));

// any file in /client/scripts will automatically be browserified,
// excluding common packages.
コード例 #3
0
ファイル: app.js プロジェクト: supratim3/cf-material
var app = express();

app.set("appconfig", config);
app.set("constants", constants);


// // Register '.mustache' extension with The Mustache Express
// app.engine('html', mustacheExpress());

// // view engine setup
// app.set('view engine', 'html');
// app.set('views', path.join(__dirname, 'views'));

nunjucks.configure('./nodeapp/views', {
    autoescape: true,
    express: app
});


app.use(logger(config.env));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/assets', express.static(path.join(__dirname, '../public')));

app.use('/', routes);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
コード例 #4
0
function njkCompile(data) {
	const templateDir = path.dirname(data["path"]);
	const config = Object.assign({"autoescape": false}, hexo.config.nunjucks);
	const env = nunjucks.configure(templateDir, config);
	return nunjucks.compile(data["text"], env, data["path"]);
}
コード例 #5
0
    inplace = require('metalsmith-in-place'),
    layouts = require('metalsmith-layouts'),
    watch = require('metalsmith-watch'),
    nunjucks = require('nunjucks'),
    extender = require('./modules/metalsmith-extends.js'),
    permalinks = require('metalsmith-permalinks'),
    json = require('metalsmith-json-to-files'),
    define = require('metalsmith-define'),
    api = require('metalsmith-json-api'),
    msriot = require('./modules/metalsmith-riot.js'),
    mingo = require('metalsmith-mingo'),
    when = require('metalsmith-if'),
    collections = require('metalsmith-collections');

// removes caching from nunjucks
var env = nunjucks.configure({noCache : true});

// build command that runs metalsmith
function build(mode, callback) {
  Metalsmith(__dirname)
    .source('./content')
    .destination('./build')
    .use(json({
      "source_path": "./json/"
    }))
    .use(collections({
       "projects": {},
       "updates": {},       
    }))
    .use(permalinks({
       pattern: ':title',
コード例 #6
0
ファイル: servidor.js プロジェクト: rrnogal/curso-node-js
console.log("Prueba: " + modelos.prueba);

//Invocamos a la funci0on de express  para crear un servidor web
var app = express();

app.use(sesion); 

app.use(bodyParser.urlencoded({
	extended : false
}));



//-----------------------Configuramos nunjucks----------------------
nunjucks.configure(__dirname + "/vistas", {
	//Le asignamos el servidor de express
	express : app
});

// Llamamos al servidor en el puerto 8080
app.listen(8080);

//logica para middleware
function validarSesion(req, res, siguienteFuncion){
	console.log("Validando sesion del usuario");
	if(typeof req.session.usuarioLogueado === "undefined"){
		res.redirect("/loguin");
	}
	siguienteFuncion();
}

//valida que un usuario sea dueño de un articulo en particular
コード例 #7
0
ファイル: fk-cache.js プロジェクト: ozum/pgexe
'use strict';

const nunjucks  = require('nunjucks');
const fs        = require('fs');
const path      = require('path');
const exec      = require('child_process').exec;

const template    = {
    normal: { create: 'create-normal-triggers.sql', drop: 'drop-normal-triggers.sql' },
    recursive: { create: 'create-recursive-triggers.sql', drop: 'drop-recursive-triggers.sql' }
};

nunjucks.configure(path.join(__dirname, '../templates'));

function getConfig(args) {
    let configFilePath  = args.configFile || 'fk-cache.json';
    // Convert file path to absolute if it is relative.
    configFilePath      = path.isAbsolute(configFilePath) ? configFilePath : path.join(process.cwd(), configFilePath);
    let config          = require(configFilePath);
    config.db           = args.options.db || config.db;
    config.user         = args.options.user || config.user;
    config.outputSchema = args.options.outputSchema || config.outputSchema;
    config.keepFiles    = args.options.keepFiles || config.keepFiles;
    return config;
}

function execute(config) {
    let cmd = `psql -f out.sql -U ${config.user} -d ${config.db};`;

    exec(cmd, (error, stdout, stderr) => {
        if (error) {
コード例 #8
0
var nunjucks = require('nunjucks');

var e = nunjucks.configure(__dirname + '/templates', {
  autoescape: true
});

module.exports = e;
コード例 #9
0
ファイル: render.js プロジェクト: Trustroots/trustroots
'use strict';

var nunjucks = require('nunjucks');

// Configure nunjucks
// https://mozilla.github.io/nunjucks/
nunjucks.configure('./modules/core/server/views', {
  watch: false,
  noCache: true
});

/**
 * Template rendering function
 * https://mozilla.github.io/nunjucks/api.html#render
 */
module.exports = nunjucks.render;
コード例 #10
0
ファイル: tutor.js プロジェクト: fxwalsh/tutor
#!/usr/bin/env node

'use strict';

const fs = require('fs');
const glob = require('glob');
const futils = require('./utils/futils');
const Lab = require('./model/lab').Lab;
const Topic = require('./model/topic').Topic;
const Course = require('./model/course.js').Course;
const nunjucks = require('nunjucks');

const root = __dirname;
nunjucks.configure(root + '/views', { autoescape: false });
nunjucks.installJinjaCompat();

if (fs.existsSync('course.md')) {
  const course = new Course('course');
  course.publish('public-site');
} else if (fs.existsSync('topic.md')) {
  const topic = new Topic('topic');
  topic.publish('public-site');
} else if (glob.sync('*.md').length > 0) {
  const lab = new Lab();
  lab.publish('../public-site/' + futils.getParentFolder());
} else {
  console.log('Unable to detect lab, topic or course');
}
コード例 #11
0
ファイル: server.js プロジェクト: jojonki/ParlAI
const bodyParser = require('body-parser');
const express = require('express');
const fs = require("fs");
const nunjucks = require('nunjucks');
const socketIO = require('socket.io');

const task_directory_name = 'task'

const PORT = process.env.PORT || 3000;

// Initialize app
const app = express()
app.use(bodyParser.json());

nunjucks.configure(task_directory_name, {
    autoescape: true,
    express: app
});

// ======================= <Routing> =======================

// Wrapper around getting the hit config details
function _load_hit_config() {
  var content = fs.readFileSync(task_directory_name+'/hit_config.json');
  return JSON.parse(content);
}

// Renders the chat page by setting up the template_context given the
// sent params for the request
app.get('/chat_index', async function (req, res) {
  var template_context = {};
  var params = req.query;
コード例 #12
0
ファイル: server.js プロジェクト: vlamanna/inker
var express = require('express');
var fs = require('fs');

var nunjucks = require('nunjucks');
var bodyParser = require('body-parser');
var emails_controller = require('./controller.emails');
var templates_controller = require('./controller.templates');
var configs = require('./configs');

var app = express();
/**
 * Setup nunjucks template base path
 * Setup nunjucks custom syntax
 */
nunjucks.configure(__dirname +"/../../dist/output/", {
    express: app,
    tags : configs.tags
});
/**
 * Accept post data
 */
app.use(bodyParser.json());   // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
  extended: true
})); 
/**
 * Routes
 */
app.get('/collections/*/templates/*', templates_controller.getOne);
app.post('/emails', emails_controller.create);
/**
 * Start server
コード例 #13
0
module.exports = function (options) {
  var defaults = {
    path: '.',
    ext: '.html',
    data: {},
    inheritExtension: false,
    envOptions: {
      watch: false
    },
    manageEnv: null
  }
  options = _.defaultsDeep(options || {}, defaults);
  nunjucks.configure(options.envOptions);

  if (!options.loaders) {
    options.loaders = new nunjucks.FileSystemLoader(options.path);
  }

  var compile = new nunjucks.Environment(options.loaders, options.envOptions);

  if (_.isFunction(options.manageEnv)) {
    options.manageEnv.call(null, compile);
  }

  /*
   * file = file
   * cb   = callback function
   */
  return through.obj(function(file, enc, cb) {
    var data = _.cloneDeep(options.data);

    if (file.isNull()) {
      this.push(file);
      return cb();
    }

    if (file.data) {
      data = _.merge(file.data, data);
    }

    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-nunjucks', 'Streaming not supported'));
      return cb();
    }

    var _this = this;

    var filePath = file.path;

    try {
      compile.renderString(file.contents.toString(), data, function (err, result) {
        if (err) {
          _this.emit('error', new gutil.PluginError('gulp-nunjucks', err, {fileName: filePath}));
          return cb();
        }
        file.contents = new Buffer(result);
        // Replace extension with mentioned/default extension
        // only if inherit extension flag is not provided(truthy)
        if (!options.inheritExtension) {
          file.path = gutil.replaceExtension(filePath, options.ext);
        }
        _this.push(file);
        cb();
      });
    } catch (err) {
      _this.emit('error', new gutil.PluginError('gulp-nunjucks', err, {fileName: filePath}));
      cb();
    }
  });
};
コード例 #14
0
ファイル: main.js プロジェクト: erikcore/clipasaurus
app.get('/', function (req, res) {
  nunjucks.configure({ autoescape: true });
  var response = nunjucks.render('templates/index.html', { });
  res.send(response)
})
コード例 #15
0
ファイル: build.js プロジェクト: BigBlueHat/website
var partial = require('metalsmith-partial')
var msstatic = require('metalsmith-static')
var serve = require('metalsmith-serve')
var watch = require('metalsmith-watch')

var nunjucks = require('nunjucks')
var njmd = require('nunjucks-markdown')
var marked = require('marked')

marked.setOptions({
  gfm: true,
  tables: true,
  smartLists: true,
})

njmd.register(nunjucks.configure(), marked);

Metalsmith(__dirname)
  .use(debug())
  .use(templates({
    "directory": ".",
    "engine": "nunjucks",
    "inPlace": true
  }))
  .use(templates({
    "directory": ".",
    "engine": "nunjucks",
  }))
  .use(msstatic({"src": "styles/", "dest": "ipfs.io/styles"}))
  .use(msstatic({"src": "media/", "dest": "ipfs.io/media"}))
  .use(msstatic({"src": "blog/", "dest": "ipfs.io/blog"}))
コード例 #16
0
var Redux = require('redux');

var CC = require('./static/app.js');


// Settings
var port = 8080;
var publicPath = path.resolve(__dirname, './static');


// Init Express
var app = express();

// Nunjucks is used for helping pre-render the DOM maybe in the future
var env = nunjucks.configure({
    express: app,
    noCache: true,
});



// Now set up the express publich path
app.use(express.static(publicPath));
app.use(bodyParser.text({type: 'application/json'}));


function renderCookieClickerMain(state) {
	var props = {
		state: state,
		onLoadGame: function(){ },
		onSaveGame: function(){ },
		onBigCookieClick: function(){ },
コード例 #17
0
ファイル: index.js プロジェクト: DirektSPEED/diet
// Create HTTP Server
var server = require('diet')
var app = server()
app.listen(3500)

// Setup Nunjucks
var nunjucks = require('nunjucks')
    nunjucks.configure(app.path+'/views', { autoescape: true, watch: true });

// Enable HTML Template
app.view('html', nunjucks.render)

// Route
app.get('/', function($){
    $.data.title = 'A nice list';
    $.data.items = [{ title: 'List Item 1' }, { title: 'List Item 2'}];
    $.end()
})
コード例 #18
0
ファイル: input-plugins.js プロジェクト: ayush2k/shared-tests
'use strict';

const nunjucks = require('nunjucks');

// const sass = require('node-sass');

/**
 *  TODO: Use the actual renderer in here
 */
nunjucks.configure({ autoescape: true });

/*
 * Common tests for input plugins
 *
 * @param {object} test ava test runner
 * @param {object} plugin input plugin
 *
 * @returns {object} plugin input plugin
 */
module.exports = function pluginTests(test, plugin) {
  let validation = [];
  let inputs = [];

  if (!test) {
    return 'you must include a test runner';
  }
  if (!plugin) {
    return 'you must include a plugin to test';
  }
  if (typeof plugin !== 'object') {
    return 'plugin must be an object';
コード例 #19
0
ファイル: express.js プロジェクト: caninojories/jrc_admin
  module.exports = function (app) {
    env.express( app );
    nunjucks.configure(path.join(rootPath, 'front-end/views'), {
      autoescape: true,
      express: app,
      watch: true,
      tags: {
        variableStart: '<$',
        variableEnd: '$>',
      }
    });
    app.set('port', process.env.PORT || 3002);
    app.set('view engine', 'html');
    app.use(compression());
    app.use(favicon(rootPath + 'front-end/resources/favicon.ico'));
    app.use(logger('dev'));
    app.use(bodyParser.urlencoded({extended:true}));
    app.use(bodyParser.json());
    app.use(multer());
    app.use(methodOverride(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(cookieParser('secret'));
    app.use(session({
                    store: new MongoStore({
                       db: 'sessions'
                    }),
                    secret: 'joriescanino',
                    /**
                     ** @cookie: { maxAge: 60000 }
                     ** Use this so that session expires
                    ***/
                    saveUninitialized: true,
                    resave: true}));

    app.use(passport.initialize());
    app.use(passport.session());
    app.use('/css', express.static(path.join(rootPath, 'front-end/resources/css')));
    app.use('/fonts', express.static(path.join(rootPath, 'front-end/resources/fonts')));
    app.use('/images', express.static(path.join(rootPath, 'front-end/resources/img')));
    app.use('/js', express.static(path.join(rootPath, 'front-end/resources/js')));
    app.use('/compileCss', express.static(path.join(rootPath, 'front-end/.tmp')));
    app.use('/bower_components', express.static(path.join(rootPath, 'front-end/bower')));
    app.use('/commonsHtml', express.static(path.join(rootPath, 'front-end/views/commons')));



    app.use(function( req, res, next ) {
      var username = req.user === undefined? '': req.user.username;
      res.adminCredentials = {isAuthenticated: req.isAuthenticated(), username: username};
      // //parserCookie(req.headers.cookie)
      // console.log( req.cookies.auth_token )

      next();
    });

  };
コード例 #20
0
    assert = require('assert'),
    ItemDAO = require('./items').ItemDAO,
    CartDAO = require('./cart').CartDAO,
    Call = require('./call').Call;
    

// Set up express
app = express();
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.set('port', (process.env.PORT || 3000));
app.use('/static', express.static(__dirname + '/static'));
app.use(bodyParser.urlencoded({ extended: true }));

var env = nunjucks.configure('views', {
    autoescape: true,
    express: app
});

var nunjucksDate = require('nunjucks-date');
nunjucksDate.setDefaultFormat('MMMM Do YYYY, h:mm:ss a');
env.addFilter("date", nunjucksDate);

var ITEMS_PER_PAGE = 5;

// Hardcoded USERID for use with the shopping cart portion
var USERID = "558098a65133816958968d88";

MongoClient.connect('mongodb://*****:*****@ds021462.mlab.com:21462/mongomart', function(err, db) {
    "use strict";

    assert.equal(null, err);
コード例 #21
0
ファイル: Gruntfile.js プロジェクト: senshu/Sozi
module.exports = function(grunt) {
    "use strict";

    var path = require("path");
    var fs = require("fs");
    var execSync = require("child_process").execSync;

    var nunjucks = require("nunjucks");
    nunjucks.configure({watch: false});

    require("load-grunt-tasks")(grunt);

    var pkg = grunt.file.readJSON("package.json");

    // Get version number from last commit date.
    // Format: YY.MM.T (year.month.timestamp).
    var rev = execSync("git show -s --format='%cI %ct'").toString().trim().split(" ");
    pkg.version = rev[0].slice(2, 4) + "." + rev[0].slice(5, 7) + "." + rev[0].slice(8, 10) + "-" + rev[1];

    var buildConfig = grunt.file.readJSON("config.default.json");
    var buildConfigJson = grunt.option("config");

    if (buildConfigJson) {
        try {
            var customBuildConfig = grunt.file.readJSON(buildConfigJson);

            grunt.verbose.writeln("Using configuration from " + buildConfigJson);

            // Overwrite default config
            for (var key in customBuildConfig) {
                buildConfig[key] = customBuildConfig[key];
            }
        }
        catch (noBuildConfigFound) {
            grunt.log.error("Configuration file " + buildConfigJson + " not found.");
        }
    }

    // Remove duplicates from an array.
    function dedup(arr) {
        return arr.filter(function (x, pos) {
            return arr.indexOf(x) === pos;
        });
    }

    // Get the OS part from a platform identifier.
    function getPlatformOS(platform) {
        return platform.split("-")[0];
    }

    // Get the architecture part from a platform identifier.
    function getPlatformArch(platform) {
        return platform.split("-")[1];
    }

    grunt.initConfig({
        pkg: pkg,

        /*
         * Check JavaScript and CSS source files.
         */
        jshint: {
            options: {
                jshintrc: true
            },
            all: [ "js/**/*.js" ]
        },

        csslint: {
            options: {
                csslintrc: ".csslintrc"
            },
            all: [ "css/**/*.css" ]
        },

        /*
         * Automatic tests.
         */
        simplemocha: {
            options: {
                timeout: 3000,
                ignoreLeaks: false,
                ui: "bdd",
                reporter: "tap"
            },
            all: {
                src: ["test/**/*.mocha.js"]
            }
        },

        /*
         * Transpile JavaScript source files from ES6 to ES5
         */
        babel: {
            options: {
                presets: ["env"]
            },
            all: {
                files: [{
                    expand: true,
                    src: ["index-webapp.js", "js/**/*.js"],
                    dest: "build/app"
                }]
            }
        },

        jspot: {
            options: {
                keyword: "_",
                parserOptions: {
                    sourceType: "module"
                }
            },
            all: {
                src: ["js/**/*.js"],
                dest: "locales"
            }
        },

        po2json: {
            options: {
                fuzzy: false,
                singleFile: true,
                nodeJs: true,
                format: "jed1.x"
            },
            all: {
                src: ["locales/*.po"],
                dest: "build/app/js/locales.js",
            }
        },

        browserify: {
            editor: {
                options: {
                    external: ["electron", "fs", "process"],
                    browserifyOptions: {
                        basedir: "build/app"
                    }
                },
                src: ["build/app/index-webapp.js"],
                dest: "build/tmp/js/editor.bundle.js"
            },
            player: {
                src: ["build/app/js/player.js"],
                dest: "build/tmp/js/player.bundle.js"
            }
        },

        /*
         * Compress the JavaScript code of the editor, player, and presenter.
         */
        uglify: {
            editor: {
                src: "<%= browserify.editor.dest %>",
                dest: "build/app/js/editor.min.js"
            },
            player: {
                src: "<%= browserify.player.dest %>",
                dest: "build/tmp/js/player.min.js"
            },
            presenter: {
                src: "build/app/js/presenter.js",
                dest: "build/tmp/js/presenter.min.js"
            }
        },

        /*
         * Precompile templates for the editor and player.
         */
        nunjucks_render: {
            player: {
                src: "templates/player.html",
                dest: "build/app/templates/player.html",
                context: {
                    playerJs: "<%= grunt.file.read('build/tmp/js/player.min.js') %>"
                }
            },
            presenter: {
                src: "templates/presenter.html",
                dest: "build/app/templates/presenter.html",
                context: {
                    presenterJs: "<%= grunt.file.read('build/tmp/js/presenter.min.js') %>"
                }
            }
        },

        copy: {
            editor: {
                files: [
                    {
                        expand: true,
                        src: [
                            "index-*.html",
                            "css/**/*",
                            "vendor/**/*"
                        ],
                        dest: "build/app"
                    }
                ]
            }
        },

        rename: {
            webapp_backend: {
                src: ["build/app/js/backend/index-webapp.js"],
                dest: "build/app/js/backend/index.js"
            },
            webapp_html: {
                src: ["build/app/index-webapp.html"],
                dest: "build/app/index.html"
            },
            electron_backend: {
                src: ["build/app/js/backend/index-electron.js"],
                dest: "build/app/js/backend/index.js"
            },
            electron_html: {
                src: ["build/app/index-electron.html"],
                dest: "build/app/index.html"
            }
        },

        compress: {
            media: {
                options: {
                    mode: "zip",
                    archive: "dist/Sozi-extras-media-<%= pkg.version %>.zip"
                },
                expand: true,
                cwd: "extras/media",
                src: ["**/*"]
            }
        },

        /*
         * Build electron applications for various platforms.
         * The options take precedence over the targets variable
         * defined later.
         */

        "install-dependencies": {
            options: {
                cwd: "build/app"
            }
        },

        electron: {
            editor: {
                options: {
                    name: "Sozi",
                    dir: "build/app",
                    out: "dist",
                    overwrite: true,
                    prune: false,
                    electronVersion: buildConfig.electronVersion,
                    platform: dedup(buildConfig.platforms.map(getPlatformOS)).join(","),
                    arch:     dedup(buildConfig.platforms.map(getPlatformArch)).join(",")
                }
            }
        },

        /*
         * Upload the web demonstration of the Sozi editor.
         */
        rsync: {
            options: {
                args: ["--verbose", "--update", "--checksum"]
            },
            editor: {
                options: {
                    src: ["build/app/*"],
                    dest: "/var/www/sozi.baierouge.fr/demo/",
                    host: "*****@*****.**",
                    deleteAll: true,
                    recursive: true
                }
            }
        },

        newer: {
            options: {
                override: function (details, include) {
                    if (details.task === "nunjucks_render") {
                        include(fs.statSync(`build/tmp/js/${details.target}.min.js`).mtime > details.time);
                    }
                    else {
                        include(false);
                    }
                }
            }
        }
    });

    /*
     * Generate installable bundles for each platform.
     */

    var debianArchs = {
        ia32: "i386",
        x64: "amd64"
    };

    var renamedOS = {
        darwin: "osx",
        win32: "windows"
    };

    buildConfig.platforms.forEach(function (platform) {
        // The folder for the current platform.
        var distDir = "dist/Sozi-" + platform;
        // Get the components of the platform.
        var platformOS   = getPlatformOS(platform);
        if (platformOS in renamedOS) {
            platformOS = renamedOS[platformOS];
        }
        var platformArch = getPlatformArch(platform);
        // The name of the target folder for the current platform in dist/.
        var bundleName = "Sozi-" + pkg.version + "-" + platformOS + "-" + platformArch;
        // The renamed folder for the current platform.
        var bundleDir = "dist/" + bundleName;

        // Copy the installation assets for the target OS.
        grunt.config(["copy", platform], {
            options: {
                mode: true
            },
            files: [
                {
                    expand: true,
                    flatten: true,
                    src: "installation-assets/" + platformOS + "/*",
                    dest: distDir + "/install/"
                },
                {
                    src: "icons/icon-256.png",
                    dest: distDir + "/install/sozi.png"
                }
            ]
        });

        // Delete the distribution folder for this platform if it exists.
        grunt.config(["clean", platform], {
            src: bundleDir
        });

        // Rename the distribution folder to the bundle name.
        grunt.config(["rename", platform], {
            src: distDir,
            dest: bundleDir
        });

        // Build zip files for Windows, tgz for other platforms.
        var bundleFormat = platformOS.startsWith("win") ? "zip" : "tgz";

        grunt.config(["compress", platform], {
            options: {
                mode: bundleFormat,
                archive: bundleDir + "." + bundleFormat
            },
            expand: true,
            cwd: "dist/",
            src: [bundleName + "/**/*"]
        });

        // Generate a Debian package for each Linux platform.
        if (platformOS === "linux" && platformArch in debianArchs) {
            grunt.config(["debian_package", platform], {
                version: pkg.version,
                platform: platform,
                arch: debianArchs[platformArch],
                date: new Date().toUTCString().slice(0, -3) + "+0000"
            });
        }
    });

    grunt.registerTask("copy-installation-assets", buildConfig.platforms.reduce(function (prev, platform) {
        var installationTask = buildConfig.installable.indexOf(getPlatformOS(platform)) >= 0 ? ["copy:" + platform] : [];
        return prev.concat(installationTask);
    }, []));

    grunt.registerTask("rename-platforms", buildConfig.platforms.reduce(function (prev, platform) {
        return prev.concat(["clean:" + platform, "rename:" + platform]);
    }, []));

    grunt.registerTask("compress-platforms", buildConfig.platforms.reduce(function (prev, platform) {
        return prev.concat(["compress:" + platform]);
    }, []));

    grunt.registerTask("write_package_json", function () {
        grunt.file.write("build/app/package.json", JSON.stringify(pkg));
    });

    grunt.registerMultiTask("nunjucks_render", function () {
        this.files.forEach(function (file) {
            grunt.file.write(file.dest, nunjucks.render(file.src[0], this.data.context));
            grunt.log.writeln("File " + file.dest + " created.");
        }, this);
    });

    grunt.registerMultiTask("debian_package", function () {
        var workDir = "dist/packaging-" + this.data.platform;
        grunt.file.write(workDir + "/Makefile",  nunjucks.render("debian/Makefile", this.data));
        grunt.file.write(workDir + "/debian/changelog", nunjucks.render("debian/changelog", this.data));
        grunt.file.write(workDir + "/debian/compat", nunjucks.render("debian/compat", this.data));
        grunt.file.write(workDir + "/debian/control", nunjucks.render("debian/control", this.data));
        grunt.file.write(workDir + "/debian/links", nunjucks.render("debian/links", this.data));
        grunt.file.write(workDir + "/debian/rules", nunjucks.render("debian/rules", this.data));
        execSync("dpkg-buildpackage -a" + this.data.arch, {cwd: workDir});
    });

    grunt.registerTask("lint", ["jshint", "csslint"]);

    grunt.registerTask("build", [
        "write_package_json",
        "newer:babel",
        "browserify:player", // Cannot use 'newer' here due to imports
        "newer:uglify:player",
        "newer:uglify:presenter",
        "newer:nunjucks_render",
        "newer:po2json",
        "newer:copy:editor",
        "compress:media"
    ]);

    grunt.registerTask("electron-build",  [
        "build",
        "rename:electron_backend",
        "rename:electron_html",
        "install-dependencies",
        "electron",
        "copy-installation-assets"
    ]);

    grunt.registerTask("web-build", [
        "build",
        "rename:webapp_backend",
        "rename:webapp_html",
        "browserify:editor", // Cannot use 'newer' here due to imports
        "newer:uglify:editor"
    ]);

    grunt.registerTask("electron-bundle", [
        "electron-build",
        "rename-platforms",
        "compress-platforms"
    ]);

    grunt.registerTask("web-demo", [
        "web-build",
        "rsync" // Cannot use 'newer' here since 'dest' is not a generated file
    ]);

    grunt.registerTask("pot", [
        "newer:babel",
        "jspot" // Cannot use 'newer' here since 'dest' is not a generated file
    ]);

    if (buildConfig.platforms.some(p => getPlatformOS(p) === "linux")) {
        grunt.registerTask("deb", [
            "electron-build",
            "rename-platforms",
            "debian_package"
        ]);

        grunt.registerTask("dist", [
            "electron-bundle",
            "debian_package"
        ]);
    }
    else {
        grunt.registerTask("dist", ["electron-bundle"]);
    }

    grunt.registerTask("default", ["electron-bundle"]);
};
コード例 #22
0
ファイル: app.js プロジェクト: cloudron-io/lets-chat
mongoose.connect(settings.database.uri, function(err) {
    if (err) {
        throw err;
    }

    //
    // express.oi Setup
    //
    if (httpsEnabled) {
        app = express().https({
            key: fs.readFileSync(settings.https.key),
            cert: fs.readFileSync(settings.https.cert),
            passphrase: settings.https.passphrase
        }).io();
    } else {
        app = express().http().io();
    }

    if (settings.env === 'production') {
        app.set('env', settings.env);
        app.set('json spaces', undefined);
        app.enable('view cache');
    }

    // Session
    var sessionStore = new MongoStore({
        mongooseConnection: mongoose.connection
    });

    // Session
    var session = {
        key: 'connect.sid',
        secret: settings.secrets.cookie,
        store: sessionStore,
        cookie: { secure: httpsEnabled },
        resave: false,
        saveUninitialized: true
    };

    // Set compression before any routes
    app.use(compression({ threshold: 512 }));

    app.use(cookieParser());
    app.io.session(session);

    auth.setup(app, session, core);

    // Security protections
    app.use(helmet.frameguard());
    app.use(helmet.hidePoweredBy());
    app.use(helmet.ieNoOpen());
    app.use(helmet.noSniff());
    app.use(helmet.xssFilter());
    app.use(helmet.hsts({
        maxAge: 31536000,
        includeSubdomains: true,
        force: httpsEnabled,
        preload: true
    }));
    app.use(helmet.contentSecurityPolicy({
        defaultSrc: ['\'none\''],
        connectSrc: ['*'],
        scriptSrc: ['\'self\'', '\'unsafe-eval\''],
        styleSrc: ['\'self\'', 'fonts.googleapis.com', '\'unsafe-inline\''],
        fontSrc: ['\'self\'', 'fonts.gstatic.com'],
        mediaSrc: ['\'self\''],
        objectSrc: ['\'self\''],
        imgSrc: ['* data:']
    }));

    var bundles = {};
    app.use(require('connect-assets')({
        paths: [
            'media/js',
            'media/less'
        ],
        helperContext: bundles,
        build: settings.env === 'production',
        fingerprinting: settings.env === 'production',
        servePath: 'media/dist'
    }));

    // Public
    app.use('/media', express.static(__dirname + '/media', {
        maxAge: '364d'
    }));

    // Templates
    var nun = nunjucks.configure('templates', {
        autoescape: true,
        express: app,
        tags: {
            blockStart: '<%',
            blockEnd: '%>',
            variableStart: '<$',
            variableEnd: '$>',
            commentStart: '<#',
            commentEnd: '#>'
        }
    });

    function wrapBundler(func) {
        // This method ensures all assets paths start with "./"
        // Making them relative, and not absolute
        return function() {
            return func.apply(func, arguments)
                       .replace(/href="\//g, 'href="./')
                       .replace(/src="\//g, 'src="./');
        };
    }

    nun.addFilter('js', wrapBundler(bundles.js));
    nun.addFilter('css', wrapBundler(bundles.css));
    nun.addGlobal('text_search', false);

    // i18n
    i18n.configure({
        directory: path.resolve(__dirname, './locales'),
        locales: settings.i18n.locales || settings.i18n.locale,
        defaultLocale: settings.i18n.locale
    });
    app.use(i18n.init);

    // HTTP Middlewares
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: true
    }));

    // IE header
    app.use(function(req, res, next) {
        res.setHeader('X-UA-Compatible', 'IE=Edge,chrome=1');
        next();
    });

    //
    // Controllers
    //
    _.each(controllers, function(controller) {
        controller.apply({
            app: app,
            core: core,
            settings: settings,
            middlewares: middlewares,
            models: models,
            controllers: controllers
        });
    });

    //
    // Go Time
    //

    if (!mongoose.mongo || !mongoose.mongo.Admin) {
        // MongoDB API has changed, assume text search is enabled
        nun.addGlobal('text_search', true);
        return;
    }

    var admin = new mongoose.mongo.Admin(mongoose.connection.db);
    admin.buildInfo(function (err, info) {
        if (err || !info) {
            return;
        }

        var version = info.version.split('.');
        if (version.length < 2) {
            return;
        }

        if(version[0] < 2) {
            return;
        }

        if(version[0] === '2' && version[1] < 6) {
            return;
        }

        nun.addGlobal('text_search', true);
    });

    var port = httpsEnabled && settings.https.port ||
               httpEnabled && settings.http.port;

    var host = httpsEnabled && settings.https.host ||
               httpEnabled && settings.http.host || '0.0.0.0';

    if (httpsEnabled && httpEnabled) {
        // Create an HTTP -> HTTPS redirect server
        var redirectServer = express();
        redirectServer.get('*', function(req, res) {
            var urlPort = port === 80 ? '' : ':' + port;
            res.redirect('https://' + req.hostname + urlPort + req.path);
        });
        http.createServer(redirectServer)
            .listen(settings.http.port || 5000, host);
    }

    app.listen(port, host);

    //
    // XMPP
    //
    if (settings.xmpp.enable) {
        var xmpp = require('./app/xmpp/index');
        xmpp(core);
    }

    var art = fs.readFileSync('./app/misc/art.txt', 'utf8');
    console.log('\n' + art + '\n\n' + 'Release ' + psjon.version.yellow + '\n');
});
コード例 #23
0
ファイル: client-gulpfile.js プロジェクト: wiledal/ducky-cms
  co(function*() {
    try {
      const nun = nunjucks.configure(`${projectPath}/templates`);
      const db = DB(projectPath);

      const contentTypes = null;
      const assets = null;

      var docs = yield db.content.find({ _type: 'doc' });

      // Resolve references
      docs.forEach((d) => {
        for (var f in d) {
          var field = d[f];
          if (!Array.isArray(field)) {
            if (field.type == 'reference') {
              d[f] = docs.filter((d2) => d2._id == field.id)[0];
            }
          }else{
            field.forEach((nestedField) => {
              if (nestedField.type == 'reference') {
                nestedField = docs.filter((d2) => d2._id == nestedField.id)[0];
              }
            })
          }
        }
      });

      // NUNJUCK GLOBALS AND FILTERS
      nun.addFilter('slugify', helpers.slugify);
      nun.addFilter('markdown', (text) => {
        if (!text) return "";
        return marked(text);
      });
      nun.addGlobal('link', (doc) => {
        if (doc._slugType == "index") return "/";
        if (doc._slugType == "no-content-type") return `/${doc._slug}`;
        return `/${doc._contentType}/${doc._slug}`;
      });
      nun.addGlobal('uploads', function(src, options) {
        var extName = path.extname(src);
        if ((extName == ".jpg" || extName == ".png" || extName == ".gif") && options) return processImage(`${projectPath}/assets/uploads/${src}`, options);
        return '/assets/uploads/' + src;
      });
      nun.addGlobal('asset', function(src, options) {
        var extName = path.extname(src);
        if ((extName == ".jpg" || extName == ".png" || extName == ".gif") && options) return processImage(`${projectPath}/assets/${src}`, options);
        return '/assets/' + src;
      });
      nun.addGlobal('content', docs);

      docs = docs.sort((a, b) => {
        if (a._createdAt > b._createdAt) return -1;
        if (a._createdAt < b._createdAt) return 1;
        return 0;
      });

      docs.forEach((doc) => {
        var contentTypeSlug = doc._contentType;
        var nameSlug = doc._slug;

        if (!doc._template) return;

        var html = nun.render(`views/${doc._template}.njk`, doc);
        try {
          var codes = helpers.extractShortcodes(html.replace(/\&quot\;/g, '"'));
        }catch(err) {
          console.log(err);
        }

        if (doc._slugType == "index") {
          fs.writeFileSync(`${projectPath}/build/index.html`, html);
        }else if (doc._slugType == "no-content-type") {
          if (!fileExists(`${projectPath}/build/${nameSlug}`)) fs.mkdirSync(`${projectPath}/build/${nameSlug}`);
          fs.writeFileSync(`${projectPath}/build/${nameSlug}/index.html`, html);
        }else{
          if (!fileExists(`${projectPath}/build/${contentTypeSlug}`)) fs.mkdirSync(`${projectPath}/build/${contentTypeSlug}`);
          fs.mkdirSync(`${projectPath}/build/${contentTypeSlug}/${nameSlug}`);
          fs.writeFileSync(`${projectPath}/build/${contentTypeSlug}/${nameSlug}/index.html`, html);
        }
      })

      done();
    }catch(err) {
      console.log(err);
      done();
    }
  })
コード例 #24
0
ファイル: gulpfile.js プロジェクト: frontui/base_static
/* 路径 */
var filePaths = {
	iconfontIE7: 'bower_components/frontui-icon/fonticon/ie7/**/**',
	iconfont: 'bower_components/frontui-icon/fonticon/fonts/**/**',
	sprite: staticPath +'/images/sprite/**/*.*',
	images: [staticPath+'/images/**/**', '!'+ staticPath +'/images/sprite/**/**'],
	less: [staticPath+'/less/**/**.less', '!'+staticPath+'/less/**/_**.less'],
	js: [staticPath+'/js/**/**',  '!'+staticPath+'/js/ui/charts', '!'+staticPath+'/js/ui/charts/**/**'],
	html: [tplPath+'/**/**.html','!'+tplPath+'/_**/*.html'],
    charts: [staticPath+'/js/ui/charts/echarts.js', staticPath+'/js/ui/charts/chart/line.js', staticPath+'/js/ui/charts/theme/paywe.js', staticPath+'/js/ui/charts/payweChart.js']
};

//模板引擎
var template = nunjucks.configure(tplPath, {
    /*
     * autoescape: true,
     * watch: true
     */
});

// 输出静态模板文件
var tpl = function(o){
    var option = {version: config.ver, dist: dist, template_url: template_url};
    if(o && typeof o === 'object') {
        for(var i in o) {
            option[i] = o[i]
        }
    }


    return through2.obj(function(file, enc, next){
        // windows环境下不用替换
コード例 #25
0
app.use(bodyParser.urlencoded({
	extended:true
}));

/*configurar vistas estaticas*/

app.use("/videos",express.static(__dirname + "/videos"));
app.use("/fuentes",express.static(__dirname + "/fuentes"));
app.use("/imagenes",express.static(__dirname + "/imagenes"));
app.use("/css",express.static(__dirname + "/css"));
app.use("/javascript",express.static(__dirname + "/javascript"));


/*configurar la carpeta de vistas*/
nunjucks.configure(__dirname + "/vistas", {
	express: app
});


/*configurar los controladores, reciben peticiones*/
app.get("/",function(req,res){
	//res.send("respondiendo a la peticion get /");
	res.render("index.html");
});

/*responder a la peticion GET /galeria*/
app.get("/galeria",function(req,res){
	//res.send("respondiendo a la peticion get /");
	res.render("galeria.html",{
		
	});
コード例 #26
0
var httpServer = !args.nosrv && !prod;
var req = !args.noreq || prod;

if (!prod) {
  // Finding the server IP
  conf.ip = args.ip
    ? 'auto' === args.ip
      ? internalIp.v4.sync()
      : args.ip
    : '127.0.0.1';
  conf.port = 9001;
  conf.baseURL = 'http://' + conf.ip + ':' + conf.port;
}
// Configure nunjuncks
Nunjucks.configure(conf.src.templates, {
  watch: watch,
  autoescape: true,
}).addFilter('date', function(date, lang) {
  return moment(date)
    .locale(lang)
    .format('LLLL');
});

// Fonts
gulp.task('build_fonts', function() {
  return gulp
    .src(conf.src.icons + '/**/*.svg', { buffer: buffer })
    .pipe(
      g.iconfont({
        fontName: 'iconsfont',
        appendCodepoints: true,
        hint: !!g.util.env.hint,
コード例 #27
0
ファイル: nunjucks.js プロジェクト: elvismircan/formio
'use strict';

var clone = require('clone');
var vm = require('vm');
var nunjucks = require('nunjucks');
var dateFilter = require('nunjucks-date-filter');
var _ = require('lodash');
var debug = {
  nunjucks: require('debug')('formio:util:nunjucks'),
  error: require('debug')('formio:error')
};
var util = require('./util');

// Configure nunjucks to not watch any files
var environment = nunjucks.configure([], {
  watch: false,
  autoescape: false
});

environment.addFilter('is_string', function(obj) {
  return _.isString(obj);
});

environment.addFilter('is_array', function(obj) {
  return _.isArray(obj);
});

environment.addFilter('is_object', function(obj) {
  return _.isPlainObject(obj);
});

environment.addFilter('date', dateFilter);
コード例 #28
0
ファイル: app.js プロジェクト: Endos-World/velochat
    fingerprinting: settings.env === 'production',
    servePath: 'media/dist'
}));

// Public
app.use('/media', express.static(__dirname + '/media', {
    maxAge: '364d'
}));

// Templates
var nun = nunjucks.configure('templates', {
    autoescape: true,
    express: app,
    tags: {
        blockStart: '<%',
        blockEnd: '%>',
        variableStart: '<$',
        variableEnd: '$>',
        commentStart: '<#',
        commentEnd: '#>'
    }
});

function wrapBundler(func) {
    // This method ensures all assets paths start with "./"
    // Making them relative, and not absolute
    return function() {
        return func.apply(func, arguments)
                   .replace(/href="\//g, 'href="./')
                   .replace(/src="\//g, 'src="./');
    };
}
コード例 #29
0
ファイル: server.js プロジェクト: Shakira4242/node-app-basics
  });
});

req.end();

req.on('error', function(e) {
  console.error(e);
});

// html_content = markdown.toHTML( importantValue );
// console.log( markdown.toHTML( importantValue ) );

// Nunjucks view engine setup
nunjucks.configure('views', {
  autoescape: true,
  express: app,
  watch: true,
});



app.set('view engine', 'html');

app.set('views', 'views');


// Set path for routes to check for static files(html/css/javascript) in
// the public folder
app.use(express.static('public'));

// Route localhost:3000 and send the text 'Page is here' to the client
コード例 #30
0
ファイル: index.js プロジェクト: metamn/pulse
'use strict';
var _ = require('lodash');
var gutil = require('gulp-util');
var through = require('through2');
var nunjucks = require('nunjucks');
nunjucks.configure({ watch: false });

module.exports = function (options, loaders, env ) {
    options = options || {};
    // ext = output file extension
    // Check if output file extension is mentioned or not
    if (options.ext === undefined) {
        // Apply default output extension
        options.ext = '.html';
    }

    var compile = nunjucks;
    if( loaders || env ){
        compile = new nunjucks.Environment( loaders, env );
    }

    /*
     * file = file
     * cb   = callback function
     */
    return through.obj(function (file, enc, cb) {

        var data = _.cloneDeep(options);

        if (file.isNull()) {
            this.push(file);