Esempio n. 1
0
	formats.forEach(function(format, i){
		if (!format) return;
		var path = typeof format === 'string' ? format : __dirname + '/../templates/' + format.template;
		var templateContent = fs.readFileSync(path, 'utf-8');
		var cssPriority = 0;
		var cssPriorityNormal = cssPriority++;
		var cssPriorityHover = cssPriority++;
		var cssPriorityActive = cssPriority++;

		// sort files based on the choosen options.sort method
		sorter.run(options.sort, files);

		options.files = files;
		options.files.forEach(function (item, i) {
			item.spritesheetWidth = options.width;
			item.spritesheetHeight = options.height;
			item.width  -= options.padding * 2;
			item.height -= options.padding * 2;
			item.x += options.padding;
			item.y += options.padding;

			item.index = i;
			if (item.trim) {
				item.trim.frameX = -item.trim.x;
				item.trim.frameY = -item.trim.y;
				item.trim.offsetX = Math.floor(Math.abs(item.trim.x + item.width / 2 - item.trim.width / 2));
				item.trim.offsetY = Math.floor(Math.abs(item.trim.y + item.height / 2 - item.trim.height / 2));
			}
			item.cssName = item.name || "";
			if (item.cssName.indexOf("_hover") >= 0) {
				item.cssName = item.cssName.replace("_hover", ":hover");
				item.cssPriority = cssPriorityHover;
			}
			else if (item.cssName.indexOf("_active") >= 0) {
				item.cssName = item.cssName.replace("_active", ":active");
				item.cssPriority = cssPriorityActive;
			}
			else {
				item.cssPriority = cssPriorityNormal;
			}
		});

		function getIndexOfCssName(files, cssName) {
			for (var i = 0; i < files.length; ++i) {
				if (files[i].cssName === cssName) {
					return i;
				}
			}
			return -1;
		};

		if (options.cssOrder) {
			var order = options.cssOrder.replace(/\./g,"").split(",");
			order.forEach(function(cssName) {
				var index = getIndexOfCssName(files, cssName);
				if (index >= 0) {
					files[index].cssPriority = cssPriority++;
				}
				else {
					console.warn("could not find :" + cssName + "css name");
				}
			});
		}

		options.files.sort(function(a, b) {
			return a.cssPriority - b.cssPriority;
		});

		options.files[options.files.length - 1].isLast = true;

		var result = Mustache.render(templateContent, options);
		function findPriority(property) {
			var value = options[property];
			var isArray = Array.isArray(value);
			if (isArray) {
				return i < value.length ? value[i] : format[property] || value[0];
			}
			return format[property] || value;
		}
		fs.writeFile(findPriority('path') + '/' + findPriority('name') + '.' + findPriority('extension'), result, callback);
	});
Esempio n. 2
0
 function render(template, target, data) {
   if (typeof target === 'string') target = dom(target)
   var compiled = mustache(templates[template], data)
   target.html(compiled)
 }
		return through.obj((file, enc, callback) => { // generate html from template
			var tpl = fs.readFileSync(template, "utf-8");
			var view = JSON.parse(file.contents.toString());
			file.contents = new Buffer(mustache.render(tpl, view));
			callback(null, file)
		})
Esempio n. 4
0
var fs = require('fs')
var marked = require('marked')
var mustache = require('mustache')

var template = fs.readFileSync('./index.mustache').toString()
var readme = fs.readFileSync('./README.md').toString()
fs.writeFileSync('./index.html', mustache.render(template, {content: marked(readme)}))
Esempio n. 5
0
module.exports = function( kspConfig, mainPath, option ){

    option = option || {};

    // Copy one.
    kspConfig = _.clone( kspConfig );

    // If need to wrap with kissy package configuration.
    var ifComboConfig = option.ifComboConfig;
    // If need to do the compress.
    var ifCompress = option.ifCompress;

    // The target file for moduleCompiler to parse.
    var inputPath = Path.resolve( EXECUTE_BASE_PATH, mainPath );
    var outPathFilename = Path.basename( mainPath, Path.extname( mainPath ) );

    // Render outputPath with Mustache. `filename` and so on... will be given as params.
    var outputPath = Path.resolve(
        EXECUTE_BASE_PATH,
        Mustache.render( kspConfig.output, {
            filename: outPathFilename,
            pub: kspConfig.pub,
            path: Path.dirname( mainPath ),
            basePath: Path.basename( Path.dirname( mainPath) )
        })
    );

    // If publish timestamp directory is specified. Than add that dir.
    // ex: `output` is 'out/index.combo.js' and set `pub` to 20120819,
    // than the final output path will be `out/pub/index.combo.js`.
    if( kspConfig.output.indexOf('{{pub}}') < 0 && typeof kspConfig.pub !== 'undefined' ){
        outputPath = Path.resolve(
            Path.resolve( Path.dirname( outputPath ), String( kspConfig.pub ) ),
            Path.basename( outputPath )
        );
    }

    // The module path of the input main module file. like `/v2/source/package/mod.js`
    var inputMainModulePath = Path.relative( kspConfig.path, inputPath );
    // The module path of the output main module file. like `v2/release/package/mod.combo.js`
    var outputMainModulePath = Path.relative( kspConfig.path, outputPath );
    // The output main module name. like `v2/release/package/mod.js`
    var outputMainModuleName = Path.join( Path.dirname( outputMainModulePath ), Path.basename( mainPath ) );

    // The extension of main module file.
    var mainModuleExtension = Path.extname( mainPath );

    // Remove file extension.
    if( mainModuleExtension ){
        outputMainModuleName = outputMainModulePath.substring( 0, outputMainModuleName.indexOf( mainModuleExtension ) );
    }

    // Compare inputPath with outputPath.
    var outputInputCompareRet = Util.pathCompare(
        Path.dirname( inputMainModulePath ),
        Path.dirname( outputMainModulePath )
    );

    // If no charset specified, auto detect it.
    if( !kspConfig.charset ){
        // === Log ===
        kspConfig.charset = Util.charsetDetect( inputPath );

        if( kspConfig === undefined ){
            Log.error( '\tCan\'t detect your file charset encoding, please specified your `charset` in `ksp.json`' );
            process.exit( 1 );
        }
        else {
            Log.info( '\tDetecting your file charset encoding: ', kspConfig.charset.toUpperCase()  );
        }
    }

    // Config module compiler.
    moduleCompiler.config({
        packages: [
            {
                name: kspConfig.name,
                path: kspConfig.path,
                charset: kspConfig.charset
            }
        ],
        // Map to replace source module name to release module name.
        // Convert `\\` --> `/` in windows.
        map: [
            [
                Util.backSlashToSlash( outputInputCompareRet[ 1 ] ),
                Util.backSlashToSlash( outputInputCompareRet[ 2 ] )
            ]
        ]
    });

    // === Log ===
    Log.info( '\tCombo all Modules into path:\n\t\t', outputPath );
    // Build!
    moduleCompiler.build( inputPath, outputPath );

    // If `outputCharset` is specified
    if( kspConfig.outputCharset && kspConfig.outputCharset.toLowerCase() != kspConfig.charset.toLowerCase() ){

        Util.fileCharsetConvert( outputPath, kspConfig.charset, kspConfig.outputCharset );
    }

    // If --wrapConfig is specified, Wrap with package config.
    if( ifComboConfig === true ){

        // === Log ===
        Log.info( '\tWrap modules with KISSY config & use.' );
        KissyConfigWrapper({
            packageName: kspConfig.name,
            mainModPath: outputMainModuleName,
            tag: kspConfig.tag,
            charset: kspConfig.outputCharset || kspConfig.charset
        }, outputPath, outputPath );
    }

    // If `compress` is specified in configuration file, ignore program.compress.
    if( kspConfig.compress !== undefined ){

        var outputExtension = Path.extname( outputPath );
        var compressOutputPath = Path.join(
            Path.dirname( outputPath ),
            Path.basename( outputPath, outputExtension ) + kspConfig.compress
            + outputExtension
        );

        // === Log ===
        Log.info( '\tCompress file into:\n\t\t', compressOutputPath );
        try{
            Compress( outputPath, compressOutputPath, { charset: kspConfig.outputCharset || kspConfig.charset } );
        }
        catch( e ){
            // === Log ===
            Log.error( '\tCompress fail! Error:', JSON.stringify( e ) );
            process.exit(1);
        }
    }
    else if( ifCompress === true ){

        // === Log ===
        Log.info( '\tCompress file into:\n\t\t', outputPath );
        try{
            Compress( outputPath, outputPath, { charset: kspConfig.outputCharset || kspConfig.charset } );
        }
        catch( e ){
            // === Log ===
            Log.error( '\tCompress fail! Error:', JSON.stringify( e ) );
            process.exit(1);
        }
    }

    // === Log ===
    Log.info( '', '\tDone' );
};
Esempio n. 6
0
 return new Promise(function (resolve) {
   resolve({
     subject: mu.render(templateName.subject, withData),
     body: mu.render(templateName.body, withData)
   });
 })
Esempio n. 7
0
// https://github.com/janl/mustache.js
const Mustache = require('mustache');

var view = {
  "beatles": [
    { "firstName": "John", "lastName": "Lennon" },
    { "firstName": "Paul", "lastName": "McCartney" },
    { "firstName": "George", "lastName": "Harrison" },
    { "firstName": "Ringo", "lastName": "Starr" }
  ],
  "name": function () {
    return this.firstName + " " + this.lastName;
  }
}

var output = Mustache.render("{{#beatles}}* {{name}}\n{{/beatles}}", view);
console.error(output);

var view2 = {
  "name": "Tater",
  "bold": function () {
    return function (text, render) {
      // 参数 text 是没有编译的节点内容 
      console.error(text);
      return "<b>" + render(text) + "</b>";
    }
  }
};

var output2 = Mustache.render("{{#bold}}Hi {{name}}.{{/bold}}", view2);
console.error(output2);
Esempio n. 8
0
File: grid.js Progetto: avdis/grid
// switch the data out with an input / select
function cellSelect(grid, $cell) {
  var template
  var data = []
  var model = getModelByIndex(grid, $cell.index())
  var type = getInputTypeFromModel(model)
  var persistedValue = getRowCellValue(grid, $cell)
  
  selectRowByCell(grid, $cell)
  
  var passBack = {
    primaryKeyValue: getSelectedRowPrimaryValue(grid),
    cellValue: persistedValue,
    cellType: type,
    model: model
  }

  grid.options.onSelectCell.call(passBack)
  grid.options.onSelectRow.call(passBack)

  // not editable
  if (!('update' in grid.options.url) || !('edit' in model) || !model.edit) {
    return
  }

  $cell.addClass(classes.selected)

  // replace html for input using data value
  if (type == 'html') {
    dialogueCellWysi.create({
      mask: true,
      hardClose: true,
      width: 500,
      html: mustache.render('<textarea class="js-grid-dialogue-wysi-textarea">{{html}}</textarea>', {html: persistedValue}),
      onClose: function() {
        cellDeselect(grid, {revert: true})
        if (typeof tinymce.activeEditor !== 'undefined') {
          tinymce.activeEditor.remove()
        }
      },
      onComplete: function() {
        tinymce.init(tinymceConfig)
      },
      actions: {
        Save: function() {
          cellDeselect(grid, {persist: true})
          dialogueCellWysi.close()
        }
      }
    })
  } else if (type == 'select') {
    template = templateSelect
    data.options = model.selectOptionsKeyValue
    data.classNames = ['grid-cell-input', classes.input]
    for (var index = data.options.length - 1; index >= 0; index--) {
      data.options[index].keySelected = persistedValue == data.options[index].key
    }
  } else {
    template = templateInput
    data = {type: 'text', value: persistedValue}
  }

  if (type != 'html') {
    $cell.html(mustache.render(template, data))
    $cell.find(gS(classes.input)).val(persistedValue).focus().select()
  }
}
Esempio n. 9
0
$(document).ready(function() {

  // Components
  var component = {

    // CSS3
    css3 : {
      name: "CSS3",
      className: "devicons devicons-css3",
      iconName:"devicons-css3"
    },

    // Bootstrap
    bootstrap : {
      name: "Bootstrap",
      className: "devicons devicons-bootstrap",
      iconName:"devicons-bootstrap"
    },

    // HTML5
    html5 : {
      name: "HTML5",
      className: "devicons devicons-html5",
      iconName:"devicons-html5"
    },

    // jQuery
    jquery: {
      name: "jQuery",
      className: "devicons devicons-jquery",
      iconName:"devicons-jquery",
      iconDescription: "A JavaScript library used to provide a View for data rendered as HTML."
    },

    // JavaScript
    javascript: {
      name: "JavaScript",
      className: "devicons devicons-javascript_badge",
      iconName:"devicons-javascript_badge"
    },

    // Mustache.js
    mustache: {
      name: "mustache.js",
      className: "devicons devicons-code",
      iconName:"devicons-code",
      iconDescription: "A logic-less HTML templating system."
    },

    // React
    react: {
      name: "React",
      className: "devicons devicons-react",
      iconName:"devicons-react",
      iconDescription: "A JavaScript library used to provide a View for data rendered as HTML."
    },

    // Sass
    sass: {
      name: "Sass",
      className: "devicons devicons-sass",
      iconName:"devicons-sass",
      iconDescription: "A CSS pre-processor with syntax advancements."
    },

    // Materialize
    materialize: {
      name: "Materialize",
      className: "devicons devicons-materializecss",
      iconName: "devicons-materializecss",
      iconDescription: "A modern responsive front-end framework based on Material Design"
    },

    // D3
    d3: {
      name: "D3.js",
      className: "devicons devicons-code",
      iconName:"devicons-code",
      iconDescription: "A JavaScript library for manipulating documents based on data."
    },

    // Node
    nodejs: {
      name: "Node.js",
      className: "devicons devicons devicons-nodejs",
      iconName: "devicons-nodejs",
      iconDescription: "Node.js is an open-source, cross-platform runtime environment for developing server-side Web applications."
    },

    // Express
    expressjs: {
      name: "Express.js",
      className: "devicons devicons-code",
      iconName: "devicons-code",
      iconDescription: "Express.js is a Node.js web application framework for creating web and network applications."
    },


  }

  // Select the template.
  var template = $("#template-portfolio-project").html();

  // Portfolio Project Data.
  var data = {

    // List of projects.
    projects: [


      {
        image: "../images/portfolio/cover-timestamp-generator.png",
        title: "Timestamp Generator Microservice",
        description: "Simple Node.js/Express.js application to convert between Natural Dates and Unix Epoch Dates",
        popout: {
          id: "portfolio-project-13"
        },
        components: [component.html5, component.css3, component.react, component.nodejs, component.expressjs],
        link: {
          github: "https://github.com/Jon1701/MS-Timestamp",
          demo: "https://ms-timestamp-jon1701.c9users.io"
        }
      },


      {
        image: "../images/portfolio/cover-requestheaderparser.png",
        title: "Request Header Parser Microservice",
        description: "Simple Node.js/Express.js application to parse web browser HTTP request headers",
        popout: {
          id: "portfolio-project-12"
        },
        components: [component.html5, component.css3, component.react, component.nodejs, component.expressjs],
        link: {
          github: "https://github.com/Jon1701/MS-RequestHeaderParser",
          demo: "https://ms-request-header-parser-jon1701.c9users.io"
        }
      },


      {
        image: "../images/portfolio/cover-recipebox.png",
        title: "Recipe Box",
        description: "Simple web application built using React.js and Materialize to store recipes using a web browser's local storage",
        popout: {
          id: "portfolio-project-1"
        },
        components: [component.html5, component.css3, component.javascript, component.react, component.materialize],
        link: {
          github: "https://github.com/Jon1701/RecipeBox",
          demo: "../portfolio/RecipeBox"
        }
      },


      {
        image: "../images/portfolio/cover-dungeoncrawler.png",
        title: "Dungeon Crawler",
        description: "A simple dungeon crawler game",
        popout: {
          id: "portfolio-project-11"
        },
        components: [component.html5, component.css3, component.javascript, component.react],
        link: {
          github: "https://github.com/Jon1701/DungeonCrawler",
          demo: "../portfolio/DungeonCrawler"
        }
      },


      {
        image: "../images/portfolio/cover-gameoflife.png",
        title: "The Game of Life",
        description: "A simulation of Conway's Game of Life, built with React.js",
        popout: {
          id: "portfolio-project-10"
        },
        components: [component.html5, component.css3, component.javascript, component.react],
        link: {
          github: "https://github.com/Jon1701/GameOfLife",
          demo: "../portfolio/GameOfLife"
        }
      },


      {
        image: "../images/portfolio/cover-d3-projects.png",
        title: "FreeCodeCamp D3 Charts",
        description: "A collection of charts made in D3",
        popout: {
          id: "portfolio-project-9"
        },
        components: [component.html5, component.css3, component.javascript, component.d3],
        link: {
          github: "https://github.com/Jon1701/FCC-D3-Projects",
          demo: "../portfolio/D3Projects"
        }
      },


      {
        image: "../images/portfolio/cover-twitch-viewer.png",
        title: "TwitchViewer",
        description: "See what some of my favourite Twitch streamers are playing",
        popout: {
          id: "portfolio-project-4"
        },
        components: [component.html5, component.css3, component.javascript, component.jquery, component.react],
        link: {
          github: "https://github.com/Jon1701/TwitchViewer",
          demo: "../portfolio/TwitchViewer"
        }
      },


      {
        image: "../images/portfolio/cover-markdown-previewer.png",
        title: "Markdown Previewer",
        description: "Converts markdown into HTML markup",
        popout: {
          id: "portfolio-project-8"
        },
        components: [component.html5, component.css3, component.javascript, component.react],
        link: {
          github: "https://github.com/Jon1701/MarkdownPreviewer",
          demo: "../portfolio/MarkdownPreviewer"
        }
      },


      {
        image: "../images/portfolio/cover-simongame.png",
        title: "Simon Game",
        description: "A classic, rebuilt for modern times, and in 4K. (Batteries not included)",
        popout: {
          id: "portfolio-project-3"
        },
        components: [component.html5, component.css3, component.javascript, component.jquery],
        link: {
          github: "https://github.com/Jon1701/SimonGame",
          demo: "../portfolio/SimonGame"
        }
      },


      {
        image: "../images/portfolio/cover-wikiviewer.png",
        title: "Wiki Viewer",
        description: "Search for Wikipedia using Wikipedia",
        popout: {
          id: "portfolio-project-5"
        },
        components: [component.html5, component.css3, component.javascript, component.jquery, component.mustache],
        link: {
          github: "https://github.com/Jon1701/WikiViewer",
          demo: "../portfolio/WikiViewer"
        }
      },


      {
        image: "../images/portfolio/cover-pumpkindoro-timer.png",
        title: "Pumpkindoro Timer",
        description: "A variation of the world famous Pomodoro Timer, now made with real pumpkins.",
        popout: {
          id: "portfolio-project-2"
        },
        components: [component.html5, component.css3, component.javascript, component.jquery],
        link: {
          github: "https://github.com/Jon1701/PumpkindoroTimer",
          demo: "../portfolio/PumpkindoroTimer"
        }
      },


      {
        image: "../images/portfolio/cover-quote-generator.png",
        title: "Life is Strange Quote Generator",
        description: "Relive the horror here with quotes from the game",
        popout: {
          id: "portfolio-project-7"
        },
        components: [component.html5, component.css3, component.javascript, component.jquery],
        link: {
          github: "https://github.com/Jon1701/LifeIsStrangeQuoteGenerator",
          demo: "../portfolio/LifeIsStrangeQuoteGenerator"
        }
      },


    ]// End list.
  } // End data

  // Parse template.
  Mustache.parse(template);

  // Render template.
  var rendered = Mustache.render(template, data);

  // Attach template.
  $("#portfolio-target").html(rendered);

});
Esempio n. 10
0
 var showmessage = function(message){
     $('.show-message').append(Mustache.render(alert_tpl, {message: message}));
 };
Esempio n. 11
0
File: grid.js Progetto: avdis/grid
function renderGridAndRead(grid) {
  grid.$container.html(mustache.render(templateGrid, grid.options))
  read(grid)
}
Esempio n. 12
0
 render: function(){
     $(this.el).html(Mustache.render(tpl, this.model));
     return this;
 },
Esempio n. 13
0
 fs.readFile(path, function (err, contents) {
     var compiled = mustache.render(contents.toString(), obj);
     return fn(null, compiled);
 });
Esempio n. 14
0
var generate = function(options){
	var APP_NAME      = options['APP_NAME'];
	var SERVER_NAME   = options['SERVER_NAME'];
	var template_dir  = options['template_dir'];
	var output_dir    = options['output_dir'];
	var view          = options['view'];
	var tools         = options['tools'];
	
	// apply functions
	tools.apply(view);
	
	// remove trailing slash
	var t_match = template_dir.match(/\/$/);
	if( t_match ){
		template_dir = template_dir.substr(0,t_match.index);
	}
	var o_match = output_dir.match(/\/$/);
	if( o_match ){
		output_dir = output_dir.substr(0,o_match.index);
	}
	
	// generate cert config
	// make path
	var template_path = template_dir + '/' + template_file;
	var output_path   = output_dir + '/' + SERVER_NAME + '/' + APP_NAME + 'Config/SSLDefaultCert.conf';
	// render and output
	var template = fs.readFileSync(template_path);
	var output = Mustache.render(template.toString(),view);
	fs.writeFileSync(output_path,output);
	
	// generate cert
	var privatekey_path = output_dir + '/' + SERVER_NAME + '/' + APP_NAME + 'Config' + '/' + APP_NAME + '.sslkey';
	var cert_path       = output_dir + '/' + SERVER_NAME + '/' + APP_NAME + 'Config' + '/' + APP_NAME + '.sslcert';
	var config_file     = output_path;
	
	var gen_privatekey  = 'openssl genrsa 2048 > ' + privatekey_path ;
	var gen_cert        = 'openssl req -new -x509 -key ' + privatekey_path + ' -out ' + cert_path + ' -config ' + config_file + ' -days 3650';
	
	console.log("generating private key");
	var child = exec(gen_privatekey,function(error,stdout,stderr){
		if( !error ){
			console.log(stdout);
			exec(gen_cert,function(error,stdout,stderr){
				if( error ){
					console.log("[generating cert] error:");
					console.log(error);
				}
				if( stderr ){
					console.log("[generating cert]stderr:");
					console.log(stderr);
				}
				if( stdout ){
					console.log(stdout);
					console.log("generated cert file");
				}
			});
		}else{
			if( error ){
				console.log("[generating private key] error:");
				console.log(error);
			}
			if( stderr ){
				console.log("[generating private key] stderr:");
				console.log(stderr);
			}
		}
	});
};
Esempio n. 15
0
 .then((template) => {
   return Mustache.render(template, { content: html })
 })
Esempio n. 16
0
			title: response[0].title.rendered,
			content: response[0].content.rendered,
		};

		return post;
	},


	/**
	 * Pages.append
	 */
	append(post) {
		// console.dir(post);
		const template = {
			title: $('#page-title').html(),
			content: $('#page-content').html(),
		};

		Mustache.parse(template.title);
		Mustache.parse(template.content);

		const htmlTitle = Mustache.render(template.title, { title: post.title });
		const htmlContent = Mustache.render(template.content, { content: post.content });

		this.$element.find('.js-title').append(htmlTitle);
		this.$element.find('.js-content').append(htmlContent);
	},
};

export default Pages;
Esempio n. 17
0
 /**
  * compile view
  *
  * @param {String} tpl - template
  * @param {Object} locals - data used by template
  *
  * @return {String} html
  *
  * @memberOf ErrorView
  */
 complieView(tpl, locals) {
   return Mustache.render(tpl, locals);
 }
Esempio n. 18
0
export function build({name, id, outputDir = path.join(__dirname, 'build'), version, icon, icon2x, style, feedBaseURL, author, documentation}) {
	const docsetDir = path.join(outputDir, name + '.docset');
	const feedDir = path.join(outputDir, 'feed');
	const userContributionDir = path.join(outputDir, 'user-contribution');

	// Version
	const timestamp = new Date();
	const docsetVersion = `${version || strftime('%F', timestamp)}/${strftime('%F_%H:%M:%S', timestamp)}`;

	fsExtra.removeSync(docsetDir);
	fsExtra.removeSync(feedDir);
	fsExtra.removeSync(userContributionDir);

	// Copy icon
	fsExtra.copySync(icon2x, docsetDir + '/icon.png');
	fsExtra.copySync(style, docsetDir + '/Contents/Resources/Documents/style.css');

	// Generate Info.plist
	fsExtra.outputFileSync(
		docsetDir + '/Contents/Info.plist',
		mustache.render(fs.readFileSync(path.join(__dirname, 'layouts/Info.plist.mustache'), 'utf-8'), {
			id: id,
			name: name,
			family: id
		}));

	// Create the database
	fsExtra.ensureDirSync(docsetDir + '/Contents/Resources');
	const db = new sqlite3.Database(docsetDir + '/Contents/Resources/docSet.dsidx');
	db.run(
		'CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, type TEXT, path TEXT)',
		function () {
			const entries = documentation.entries;
			const pages = documentation.pages;

			// Generate pages
			forEach(pages, (page) => {
				fsExtra.outputFileSync(
					path.join(docsetDir, 'Contents/Resources/Documents/' + page.id + '.html'), 
					isString(page.html) ? page.html : ReactDOMServer.renderToStaticMarkup(page.html));
			});

			// Insert entries into database
			forEach(entries, (entry) => {
				db.run('INSERT OR IGNORE INTO searchIndex(name, type, path) VALUES (?, ?, ?)', 
					entry.name, entry.type, entry.id + '.html#' + entry.anchor);
			});

			db.close();
		
			// Generate index.html
			fsExtra.outputFileSync(
				path.join(docsetDir, 'Contents/Resources/Documents/index.html'),
				ReactDOMServer.renderToStaticMarkup(
					<Index title={name} pages={pages} />
				)
			);
				
			// Render the feed
			const feed = path.join(feedDir, name + '.xml');
			fsExtra.outputFileSync(
				feed,
				mustache.render(fs.readFileSync('layouts/feed.xml.mustache', 'utf-8'), {
					version: docsetVersion,
					url: feedBaseURL + '/' + name + '.tgz'
				}));
			fsExtra.outputFileSync(
				path.join(feedDir, name + '.html'),
				ReactDOMServer.renderToStaticMarkup(
					<Feed 
						feed={'dash-feed://' + encodeURIComponent(feedBaseURL + '/' + name + '.xml')}
						name={name} />
				)
			);
			
			// Tar everything up into a tarball
			fstream.Reader({ path: docsetDir, type: 'Directory'})
				.pipe(tar.Pack({noProprietary: true}))
				.pipe(zlib.createGzip())
				.pipe(fs.createWriteStream(feedDir + '/' + name + '.tgz'));

			// Generate a Dash user contribution dir
			fsExtra.outputFileSync(
				userContributionDir + '/docset.json',
				mustache.render(fs.readFileSync('layouts/docset.json.mustache', 'utf-8'), {
					name: name,
					author: author.name,
					authorLink: author.url,
					version: docsetVersion
				}));
			fsExtra.copySync(icon2x, userContributionDir + '/icon@2x.png');
			fsExtra.copySync(icon, userContributionDir + '/icon.png');
			fstream.Reader({ path: docsetDir, type: 'Directory'})
				.pipe(tar.Pack({noProprietary: true}))
				.pipe(zlib.createGzip())
				.pipe(fs.createWriteStream(userContributionDir + '/' + name + '.tgz'));
		});
}
Esempio n. 19
0
 .then(function (template) {
   return {
     subject: mu.render(template.subject, withData),
     body: mu.render(template.body, withData)
   };
 });
Esempio n. 20
0
		function () {
			const entries = documentation.entries;
			const pages = documentation.pages;

			// Generate pages
			forEach(pages, (page) => {
				fsExtra.outputFileSync(
					path.join(docsetDir, 'Contents/Resources/Documents/' + page.id + '.html'), 
					isString(page.html) ? page.html : ReactDOMServer.renderToStaticMarkup(page.html));
			});

			// Insert entries into database
			forEach(entries, (entry) => {
				db.run('INSERT OR IGNORE INTO searchIndex(name, type, path) VALUES (?, ?, ?)', 
					entry.name, entry.type, entry.id + '.html#' + entry.anchor);
			});

			db.close();
		
			// Generate index.html
			fsExtra.outputFileSync(
				path.join(docsetDir, 'Contents/Resources/Documents/index.html'),
				ReactDOMServer.renderToStaticMarkup(
					<Index title={name} pages={pages} />
				)
			);
				
			// Render the feed
			const feed = path.join(feedDir, name + '.xml');
			fsExtra.outputFileSync(
				feed,
				mustache.render(fs.readFileSync('layouts/feed.xml.mustache', 'utf-8'), {
					version: docsetVersion,
					url: feedBaseURL + '/' + name + '.tgz'
				}));
			fsExtra.outputFileSync(
				path.join(feedDir, name + '.html'),
				ReactDOMServer.renderToStaticMarkup(
					<Feed 
						feed={'dash-feed://' + encodeURIComponent(feedBaseURL + '/' + name + '.xml')}
						name={name} />
				)
			);
			
			// Tar everything up into a tarball
			fstream.Reader({ path: docsetDir, type: 'Directory'})
				.pipe(tar.Pack({noProprietary: true}))
				.pipe(zlib.createGzip())
				.pipe(fs.createWriteStream(feedDir + '/' + name + '.tgz'));

			// Generate a Dash user contribution dir
			fsExtra.outputFileSync(
				userContributionDir + '/docset.json',
				mustache.render(fs.readFileSync('layouts/docset.json.mustache', 'utf-8'), {
					name: name,
					author: author.name,
					authorLink: author.url,
					version: docsetVersion
				}));
			fsExtra.copySync(icon2x, userContributionDir + '/icon@2x.png');
			fsExtra.copySync(icon, userContributionDir + '/icon.png');
			fstream.Reader({ path: docsetDir, type: 'Directory'})
				.pipe(tar.Pack({noProprietary: true}))
				.pipe(zlib.createGzip())
				.pipe(fs.createWriteStream(userContributionDir + '/' + name + '.tgz'));
		});
Esempio n. 21
0
Cleaver.prototype.renderAuthorSlide = function (content) {
    return mustache.render(this.templates.loaded.author, content);
};
Esempio n. 22
0
 var renderList = function(dataObj) {
     var $html = $(Mustache.render(temp(), dataObj));
     box.append($html);
 }
Esempio n. 23
0
    // Render our template and then save the file
    function renderTemplate(file) {
        var compiled = mustache.render(file.contents, file.data);

        fs.writeFile(file.dest, compiled);
    }
Esempio n. 24
0
module.exports = function(formatter_type, data){
  location = 'templates/_formatters/'
  return Mustache.render(fs.readFileSync(location + formatter_type + ".html", 'utf-8'),data)
}
Esempio n. 25
0
 async.each(config.accounts, function(conf) {
   postTweet(mustache.render(conf.template_removed, {
     url: record.url,
     ip: record.ip}), conf.tokens);
 });
Esempio n. 26
0
var fs = require('fs');
var Mustache = require('mustache');

var noun = process.argv[4];
var adjective = process.argv[5];
var verb = process.argv[6];
var noun2 = process.argv[7];

var story = fs.readFileSync('./stories/story1.txt', 'utf8');

var updatedStory = Mustache.render(story, {"noun" : noun, "adjective": adjective,"verb": verb, "noun2": noun2});

console.log(updatedStory);
Esempio n. 27
0
i18n.__n = function i18nTranslatePlural(singular, plural, count) {
  var msg, namedValues, args = [];
  
  // Accept an object with named values as the last parameter
  if (
    arguments.length >= 2 &&
    arguments[arguments.length - 1] !== null && 
    typeof arguments[arguments.length - 1] === "object"
  ) {
    namedValues = arguments[arguments.length - 1];
    args = arguments.length >= 5 ? Array.prototype.slice.call(arguments, 3, -1) : [];
  } else {
    namedValues = {};
    args = arguments.length >= 4 ? Array.prototype.slice.call(arguments, 3) : [];
  }
  
  // called like __n({singular: "%s cat", plural: "%s cats", locale: "en"}, 3)
  if (typeof singular === 'object') {
    if (typeof singular.locale === 'string' && typeof singular.singular === 'string' && typeof singular.plural === 'string') {
      msg = translate(singular.locale, singular.singular, singular.plural);
    }
    args.unshift(count);
    // some template engines pass all values as strings -> so we try to convert them to numbers
    if (typeof plural === 'number' || parseInt(plural, 10)+"" === plural) {
      count = plural;
    }

    // called like __n({singular: "%s cat", plural: "%s cats", locale: "en", count: 3})
    if(typeof singular.count === 'number' || typeof singular.count === 'string'){
      count = singular.count;
      args.unshift(plural);      
    }
  }
  else {
    // called like  __n('cat', 3)
    if (typeof plural === 'number' || parseInt(plural, 10)+"" === plural) {
      count = plural;
      args.unshift(count);
      args.unshift(plural);
    }
    // called like __n('%s cat', '%s cats', 3)
    // get translated message with locale from scope (deprecated) or object
    msg = translate(getLocaleFromObject(this), singular, plural);
  }
  if (count == null) count = namedValues.count;

  // parse translation and replace all digets '%d' by `count`
  // this also replaces extra strings '%%s' to parseble '%s' for next step
  // simplest 2 form implementation of plural, like https://developer.mozilla.org/en/docs/Localization_and_Plurals#Plural_rule_.231_.282_forms.29
  if (count > 1) {
    msg = vsprintf(msg.other, [parseInt(count, 10)]);
  } else {
    msg = vsprintf(msg.one, [parseInt(count, 10)]);
  }
  
  // if the msg string contains {{Mustache}} patterns we render it as a mini tempalate
  if ((/{{.*}}/).test(msg)) {
    msg = Mustache.render(msg, namedValues);
  }
  
  // if we have extra arguments with strings to get replaced,
  // an additional substition injects those strings afterwards
  if ((/%/).test(msg) && args && args.length > 0) {
    msg = vsprintf(msg, args);
  }

  return msg;
};
Esempio n. 28
0
        this.on("input",function(msg) {
            var preRequestTimestamp = process.hrtime();
            node.status({fill:"blue",shape:"dot",text:"httpin.status.requesting"});
            var url = nodeUrl || msg.url;
            if (msg.url && nodeUrl && (nodeUrl !== msg.url)) {  // revert change below when warning is finally removed
                node.warn(RED._("common.errors.nooverride"));
            }
            if (isTemplatedUrl) {
                url = mustache.render(nodeUrl,msg);
            }
            if (!url) {
                node.error(RED._("httpin.errors.no-url"),msg);
                return;
            }
            // url must start http:// or https:// so assume http:// if not set
            if (!((url.indexOf("http://") === 0) || (url.indexOf("https://") === 0))) {
                url = "http://"+url;
            }

            var method = nodeMethod.toUpperCase() || "GET";
            if (msg.method && n.method && (n.method !== "use")) {     // warn if override option not set
                node.warn(RED._("common.errors.nooverride"));
            }
            if (msg.method && n.method && (n.method === "use")) {
                method = msg.method.toUpperCase();          // use the msg parameter
            }
            var opts = urllib.parse(url);
            opts.method = method;
            opts.headers = {};
            if (msg.headers) {
                for (var v in msg.headers) {
                    if (msg.headers.hasOwnProperty(v)) {
                        var name = v.toLowerCase();
                        if (name !== "content-type" && name !== "content-length") {
                            // only normalise the known headers used later in this
                            // function. Otherwise leave them alone.
                            name = v;
                        }
                        opts.headers[name] = msg.headers[v];
                    }
                }
            }
            if (this.credentials && this.credentials.user) {
                opts.auth = this.credentials.user+":"+(this.credentials.password||"");
            }
            var payload = null;

            if (msg.payload && (method == "POST" || method == "PUT" || method == "PATCH" ) ) {
                if (typeof msg.payload === "string" || Buffer.isBuffer(msg.payload)) {
                    payload = msg.payload;
                } else if (typeof msg.payload == "number") {
                    payload = msg.payload+"";
                } else {
                    if (opts.headers['content-type'] == 'application/x-www-form-urlencoded') {
                        payload = querystring.stringify(msg.payload);
                    } else {
                        payload = JSON.stringify(msg.payload);
                        if (opts.headers['content-type'] == null) {
                            opts.headers['content-type'] = "application/json";
                        }
                    }
                }
                if (opts.headers['content-length'] == null) {
                    if (Buffer.isBuffer(payload)) {
                        opts.headers['content-length'] = payload.length;
                    } else {
                        opts.headers['content-length'] = Buffer.byteLength(payload);
                    }
                }
            }
            var urltotest = url;
            var noproxy;
            if (noprox) {
                for (var i in noprox) {
                    if (url.indexOf(noprox[i]) !== -1) { noproxy=true; }
                }
            }
            if (prox && !noproxy) {
                var match = prox.match(/^(http:\/\/)?(.+)?:([0-9]+)?/i);
                if (match) {
                    //opts.protocol = "http:";
                    //opts.host = opts.hostname = match[2];
                    //opts.port = (match[3] != null ? match[3] : 80);
                    opts.headers['Host'] = opts.host;
                    var heads = opts.headers;
                    var path = opts.pathname = opts.href;
                    opts = urllib.parse(prox);
                    opts.path = opts.pathname = path;
                    opts.headers = heads;
                    opts.method = method;
                    //console.log(opts);
                    urltotest = match[0];
                }
                else { node.warn("Bad proxy url: "+process.env.http_proxy); }
            }
            var req = ((/^https/.test(urltotest))?https:http).request(opts,function(res) {
                (node.ret === "bin") ? res.setEncoding('binary') : res.setEncoding('utf8');
                msg.statusCode = res.statusCode;
                msg.headers = res.headers;
                msg.payload = "";
                // msg.url = url;   // revert when warning above finally removed
                res.on('data',function(chunk) {
                    msg.payload += chunk;
                });
                res.on('end',function() {
                    if (node.metric()) {
                        // Calculate request time
                        var diff = process.hrtime(preRequestTimestamp);
                        var ms = diff[0] * 1e3 + diff[1] * 1e-6;
                        var metricRequestDurationMillis = ms.toFixed(3);
                        node.metric("duration.millis", msg, metricRequestDurationMillis);
                        if (res.client && res.client.bytesRead) {
                            node.metric("size.bytes", msg, res.client.bytesRead);
                        }
                    }
                    if (node.ret === "bin") {
                        msg.payload = new Buffer(msg.payload,"binary");
                    }
                    else if (node.ret === "obj") {
                        try { msg.payload = JSON.parse(msg.payload); }
                        catch(e) { node.warn(RED._("httpin.errors.json-error")); }
                    }
                    node.send(msg);
                    node.status({});
                });
            });
            req.on('error',function(err) {
                msg.payload = err.toString() + " : " + url;
                msg.statusCode = err.code;
                node.send(msg);
                node.status({fill:"red",shape:"ring",text:err.code});
            });
            if (payload) {
                req.write(payload);
            }
            req.end();
        });
Esempio n. 29
0
  const Slice = function (data, controller) {
    let timer;
    const token = $('#' + data.token);
    const containerId = data.token + '_con';
    const selector = '#' + containerId;
    const container = $(selector);
    const sliceId = data.slice_id;
    const origJsonEndpoint = data.json_endpoint;
    let dttm = 0;
    const stopwatch = function () {
      dttm += 10;
      const num = dttm / 1000;
      $('#timer').text(num.toFixed(2) + ' sec');
    };
    let qrystr = '';
    slice = {
      data,
      container,
      containerId,
      selector,
      querystring() {
        const parser = document.createElement('a');
        parser.href = data.json_endpoint;
        if (controller.type === 'dashboard') {
          parser.href = origJsonEndpoint;
          let flts = controller.effectiveExtraFilters(sliceId);
          flts = encodeURIComponent(JSON.stringify(flts));
          qrystr = parser.search + '&extra_filters=' + flts;
        } else if ($('#query').length === 0) {
          qrystr = parser.search;
        } else {
          qrystr = '?' + $('#query').serialize();
        }
        return qrystr;
      },
      getWidgetHeader() {
        return this.container.parents('div.widget').find('.chart-header');
      },
      render_template(s) {
        const context = {
          width: this.width,
          height: this.height,
        };
        return Mustache.render(s, context);
      },
      jsonEndpoint() {
        const parser = document.createElement('a');
        parser.href = data.json_endpoint;
        let endpoint = parser.pathname + this.querystring();
        if (endpoint.charAt(0) !== '/') {
          // Known issue for IE <= 11:
          // https://connect.microsoft.com/IE/feedbackdetail/view/1002846/pathname-incorrect-for-out-of-document-elements
          endpoint = '/' + endpoint;
        }
        endpoint += '&json=true';
        endpoint += '&force=' + this.force;
        return endpoint;
      },
      d3format(col, number) {
        // uses the utils memoized d3format function and formats based on
        // column level defined preferences
        const format = data.column_formats[col];
        return utils.d3format(format, number);
      },
      /* eslint no-shadow: 0 */
      always(data) {
        clearInterval(timer);
        $('#timer').removeClass('btn-warning');
        if (data && data.query) {
          slice.viewSqlQuery = data.query;
        }
      },
      done(payload) {
        Object.assign(data, payload);

        clearInterval(timer);
        token.find('img.loading').hide();
        container.fadeTo(0.5, 1);
        container.show();

        $('#timer').addClass('label-success');
        $('#timer').removeClass('label-warning label-danger');
        $('.query-and-save button').removeAttr('disabled');
        this.always(data);
        controller.done(this);
      },
      getErrorMsg(xhr) {
        if (xhr.statusText === 'timeout') {
          return 'The request timed out';
        }
        let msg = '';
        if (!xhr.responseText) {
          const status = xhr.status;
          msg += 'An unknown error occurred. (Status: ' + status + ')';
          if (status === 0) {
            // This may happen when the worker in gunicorn times out
            msg += ' Maybe the request timed out?';
          }
        }
        return msg;
      },
      error(msg, xhr) {
        let errorMsg = msg;
        token.find('img.loading').hide();
        container.fadeTo(0.5, 1);
        let errHtml = '';
        let o;
        try {
          o = JSON.parse(msg);
          if (o.error) {
            errorMsg = o.error;
          }
        } catch (e) {
          // pass
        }
        errHtml = `<div class="alert alert-danger">${errorMsg}</div>`;
        if (xhr) {
          const extendedMsg = this.getErrorMsg(xhr);
          if (extendedMsg) {
            errHtml += `<div class="alert alert-danger">${extendedMsg}</div>`;
          }
        }
        container.html(errHtml);
        container.show();
        $('span.query').removeClass('disabled');
        $('#timer').addClass('btn-danger');
        $('.query-and-save button').removeAttr('disabled');
        this.always(o);
        controller.error(this);
      },
      clearError() {
        $(selector + ' div.alert').remove();
      },
      width() {
        return token.width();
      },
      height() {
        let others = 0;
        const widget = container.parents('.widget');
        const sliceDescription = widget.find('.slice_description');
        if (sliceDescription.is(':visible')) {
          others += widget.find('.slice_description').height() + 25;
        }
        others += widget.find('.chart-header').height();
        return widget.height() - others - 10;
      },
      bindResizeToWindowResize() {
        let resizeTimer;
        const slice = this;
        $(window).on('resize', function () {
          clearTimeout(resizeTimer);
          resizeTimer = setTimeout(function () {
            slice.resize();
          }, 500);
        });
      },
      render(force) {
        if (force === undefined) {
          this.force = false;
        } else {
          this.force = force;
        }
        token.find('img.loading').show();
        container.fadeTo(0.5, 0.25);
        container.css('height', this.height());
        dttm = 0;
        timer = setInterval(stopwatch, 10);
        $('#timer').removeClass('label-danger label-success');
        $('#timer').addClass('label-warning');
        this.viz.render();
      },
      resize() {
        token.find('img.loading').show();
        container.fadeTo(0.5, 0.25);
        container.css('height', this.height());
        this.viz.render();
        this.viz.resize();
      },
      addFilter(col, vals) {
        controller.addFilter(sliceId, col, vals);
      },
      setFilter(col, vals) {
        controller.setFilter(sliceId, col, vals);
      },
      getFilters() {
        return controller.filters[sliceId];
      },
      clearFilter() {
        controller.clearFilter(sliceId);
      },
      removeFilter(col, vals) {
        controller.removeFilter(sliceId, col, vals);
      },
    };
    slice.viz = vizMap[data.form_data.viz_type](slice);
    return slice;
  };
Esempio n. 30
0
module.exports = function(ast, templateDir, isIndex, sort) {
  if (!ast) { throw new Error('no analyzed ast to generate markdown from'); }

  var templates;

  if (!templateDir) {
    templateDir = path.resolve(__dirname, '../templates');
  } else {
    templateDir = templateDir.replace(/\\/g, '/');
  }

  var tags = (ast.modules || [])
      .concat(ast.classes || [])
      .concat(ast.functions || []);
  var targets = {};
  tags.forEach(function (tag) {
    if (tag.longname) {
      tag.target = targets[tag.longname] = '#' + tag.longname.toLowerCase();
    }
  });

  //if ast is an index file, we need to sort the contents and to use the right templates;
  if (isIndex) {
    console.log('Now generating index');
    var sortFn;
    if (sort === 'none') {
      sortFn = null;
    } else if (sort === 'namespace') {
      sortFn = function(a, b) {
        var namespaceA = a.longname.split('.').slice(0, -1);
        var namespaceB = b.longname.split('.').slice(0, -1);
        if (namespaceA < namespaceB) {
          return -1;
        }
        if (namespaceA > namespaceB) {
          return 1;
        }
        return a.name < b.name ? -1 : 1;
      };
    } else {
      sortFn = function(a, b) {
        return a.name < b.name ? -1 : 1;
      };
    }
    if (sortFn !== null) {
      ast.classes.sort(sortFn);
      ast.functions.sort(sortFn);
    }

    templates = {
      index: fs.readFileSync(templateDir + '/index.mustache', 'utf8'),
      class: fs.readFileSync(templateDir + '/overview.mustache', 'utf8'),//do we need different overview templates for functions or classes here ?
      function: fs.readFileSync(templateDir + '/overview.mustache', 'utf8')
    };
    return Mustache.render(templates.index, ast, templates);
  }

  tags.forEach(function (tag) {
    processTag(tag, targets);
  });

  templates = {
    file: fs.readFileSync(templateDir + '/file.mustache', 'utf8'),
    class: fs.readFileSync(templateDir + '/class.mustache', 'utf8'),
    function: fs.readFileSync(templateDir + '/function.mustache', 'utf8')
  };
  return Mustache.render(templates.file, ast, templates);
};