Example #1
0
      getLayout(layoutFileName, function (err, start, end) {
        if (err) {
          self.emit('error',
            new gutil.PluginError('gulp-liquid', 'Cannot find template file: ' + layoutFileName));
          return callback();
        }

        // the data that get's put into the template is made from the file's frontmatter and the options passed in.
        var data =_.extend({}, file.page, opts.locals);

        // we create the template on the fly, it is made from the start of the
        // layout file, followed by the full contents of the file we are working
        // on followed by the end of the layout file.
        engine
          .parse(start + '\n' + file.contents.toString() + '\n' + end)
          .then(function(template) {
            return template.render(data);
          })
          .then(function (output) {
            file.contents = new Buffer(output);
            self.push(file);
            callback();
          });

      });
Example #2
0
function renderLeftPannel() {

	return lengine.parseAndRender( fs.readFileSync( './app/html/leftpannel.html'), exports.getTplData() ).then( function( html ) {
		IO.globalOut("updateleftpannel", html );
	} );

}
Example #3
0
 renderBody() {
   debug('= Email.renderBody', 'Rendering body with template', this.body, 'and metadata', this.metadata);
   const unsubscribeUrl = this._buildUnsubscribeUrl();
   const extraFields = { recipient_email: this.to, from_email: this.from, unsubscribe_url: unsubscribeUrl };
   const metadata = Object.assign({}, this.metadata, extraFields);
   return liquid.parseAndRender(this.body, metadata)
     .then(parsedBody => this._appendFooter(parsedBody));
 }
Example #4
0
  * writeView(name, dest) {
    if (!dest) {
      throw new Error('Please specify destination folder')
    }
    const src = path.join(this.root, 'src')
    const engine = new Liquid.Engine

    engine.registerFileSystem(
      new Liquid.LocalFileSystem(path.join(src, '_includes'))
    )
    const view = yield readFile(path.join(src, name), 'utf8')
    const template = yield engine.parse(view)
    const result = yield template.render(this)

    yield writeFile(path.join(dest, name), result)
    debug('wrote %s', name)
  }
Example #5
0
 fs.readFile(filePath, 'utf8', (err, data) => {
   if (err) {
     return console.log(err);
   }
   engine
   .parseAndRender(data, Object.assign({}, obj))
   .then(result => {
     resolve(result);
   });
 });
Example #6
0
 dataReader = fs.readFile("./src/kittens.json", 'utf8', function (err, data) {
     if (err) {
         // TODO handle that
     }
     var jsonKittens = JSON.parse(data);
     log.info({requestCount: requestCount, dataLength: jsonKittens.kittens.length}, 'kittens data loaded');
     lqEngine.parse(templateF).then(function (template) {
         return template.render({date: new Date, kittens: jsonKittens.kittens});
     }).then(function (result) {
         res.end(result);
     });
 });
Example #7
0
const parseChunk = (chunk) => {
  return engine
    .parse(chunk)
    .catch((err) => {
      if(err.name === "Liquid.SyntaxError") {
        const problemReg = /at (.*) /;
        const length = err.message.match(problemReg)[1].length;
        err.location.lenght = length;
        errors.push(err);
      }
      chunk = replaceProblemWithSpace(chunk, err);
      return parseChunk(chunk);
    });
};
Example #8
0
  var gulpPrefixer = function () {

    var through   = require('through2');
    var Liquid     = require('liquid-node');
    var liquidEngine = new Liquid.Engine();
    var togError = require('./togErrors');

    opts = opts || {};

    if ( opts.tags && typeof opts.tags === 'object' ) {
      // Register liquid tags prior to processing
      Object.keys(opts.tags).forEach(function (tag) {
        Liquid.Template.registerTag(tag, opts.tags[tag]);
      });
    }

    function liquid (file, enc, callback) {
      /*jshint validthis:true */
      var template;
      var promise;

      if (file.isNull()) {
        return callback();
      }

      if (file.isStream()) {
        this.emit('error', togError.noStreamSupport(PLUGIN_NAME));
        return callback();
      }

      if (file.isBuffer()) {
        template = liquidEngine.parse(file.contents.toString());
        promise = template.render(file.togMetadata.options);

        promise.then(function (output) {
          file.contents = Buffer.from(output);
          this.push(file);
          callback();
        }.bind(this), function (err) {
          this.emit('error', togError.error(PLUGIN_NAME, 'Error during conversion: ' + err));
          return callback();
        });
      }
    }

    return through.obj(liquid);
  };
app.post('/cta-submitted', function (req, res) {
  liquid.parseAndRender(template, req.body).then(function (html) {
    sendgrid.send({
      from: config.from,
      to: config.to,
      subject: config.subject,
      html: html
    }, function (err, json) {
      if (err) {
        console.error(err)
        res.status(500)
        res.json({'errors': [{'message': json}]})
      } else {
        res.status(200)
      }
      res.end()
    })
  })
})
Example #10
0
	IO.onGlobalMessage( "getmethodconfiguration", function( d ) {

		var method = JSON.parse( fs.readFileSync( d.method + "/config.json" ) );

		lengine.parseAndRender( fs.readFileSync( d.method + "/configform.html" ), extend( true, {}, { method: method }, exports.getTplData() ) ).then( function( data ) {

			var fill;
			for( var i = 0, l = usedMethods.length; i < l ; i ++ ) {
				if( usedMethods[ i ].id == d.methodid ) {
					fill = usedMethods[ i ].config;
					break;
				}
			}
			
			IO.globalOut( "methodconfiguration", { form: data, fill: fill } );

		});

	} );
Example #11
0
/*global Meteor, check */



import { api, Lava } from "../../../util/rock"
import { makeNewGuid } from "../../../util"


// @TODO abstract
import Liquid from "liquid-node"
const Parser = new Liquid.Engine

Parser.registerFilters({
  Attribute: function(variable, key){

    if (variable === "Global") {
      let global = this.context.findVariable("GlobalAttribute")
      return global.then((response) => {
        return response[key]
      })
    }

  },
  Format: function(value, format){

    // hardcode number formating for now
    if (format === "#,##0.00") {
      value = Number(value).toFixed(2)

      return `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    }
Example #12
0
/* eslint-env node */
/* eslint no-console: 0 strict: 0 */
'use strict';

let Liquid = require('liquid-node'),
  fs = require('mz/fs'),
  engine = new Liquid.Engine;

class CustomFileSystem extends Liquid.BlankFileSystem {
  readTemplateFile (path) {
    return fs.readFile(`tests/pages/_includes/${path}`, 'utf8');
  }
}

class StripTag extends Liquid.Block {
  render (context) {
    return super.render(context).then(function (chunks) {
      // let text = chunks.join('');
      let text = flatten(chunks).join('');
      let stripped = String(text).replace(/^\s+|\s+$/g, '');
      return stripped;
    });
  }
}

function flatten (_array) {
  return _array.reduce(function (a, b) {
    if (Array.isArray(b)) {
      return a.concat(flatten(b));
    }
    return a.concat(b);
Example #13
0
 renderSubject() {
   debug('= Email.renderSubject', 'Rendering subject with template', this.subject, 'and metadata', this.metadata);
   return liquid.parseAndRender(this.subject, this.metadata);
 }
Example #14
0
 renderBody() {
   debug('= Email.renderBody', 'Rendering body with template', this.body, 'and metadata', this.metadata);
   return liquid.parseAndRender(this.body, this.metadata);
 }
Example #15
0
 return $b.props(_.mapValues(_files, (content) => {
     // (3) Render then content with config
     return engine.parseAndRender(content, config)
 }))
Example #16
0
let { $fs, $b, _ } = require('zaccaria-cli')
let html = require('remark-html');
// Use xhtml for remark to force self closing tags..
let $r = require('remark')().use(html, {xhtml: true, entities: 'numbers'});
let Liquid = require("liquid-node")
let engine = new Liquid.Engine
let datejs = require('moment')

let { warn, info, error } = require('./messages')

function toMarkdown(content) {
    return $r.process(content)
}

let files = {
    '/course.xml': $fs.readFileSync(__dirname+'/../templates/course.xml', 'utf-8'),
    '/about/overview.html': $fs.readFileSync(__dirname+'/../templates/overview.html', 'utf-8'),
    '/about/short_description.html': $fs.readFileSync(__dirname+'/../templates/short_description.html', 'utf-8')
}

engine.registerFilters({
    markdown: $r.process,
    datejs: (input) => {
        return datejs(new Date(input)).toISOString()
    }
})


function expandTemplates(config) {
    config.originalFiles = $b.props(files)
    config.expandedFiles = config.originalFiles.then((_files) => {
 _buildBody(body, metadata = {}) {
   return liquid.parseAndRender(body, this.metadata);
 }
Example #18
0
  "communication/email/send": function(emailId, PersonAliasId, mergeFields){
    check(emailId, Number)
    // check(PersonAliasId, Number)

    let Email = api.get.sync(`SystemEmails/${emailId}`)

    if (!Email.Body || !Email.Subject) {
      throw new Meteor.Error(`No email body or subject found for ${emailId}`)
    }

    /*

      Get global attributes from Rock and map to JSON

      @TODO depreciate for MergeFieldsJson

    */
    const GlobalAttribute = {}
    const Globals = api.get.sync("AttributeValues?$filter=Attribute/EntityTypeId eq null&$expand=Attribute&$select=Attribute/Key,Value")
    const Defaults = api.get.sync("Attributes?$filter=EntityTypeId eq null&$select=DefaultValue,Key")

    for (let d of Defaults) { GlobalAttribute[d.Key] = d.DefaultValue }
    for (let g of Globals) { GlobalAttribute[g.Attribute.Key] = g.Value }
    mergeFields = {...mergeFields, ...{ GlobalAttribute }}

    return Promise.all([
      Parser.parseAndRender(Email.Subject, mergeFields),
      Parser.parseAndRender(Email.Body, mergeFields)
      // Lava.render(Email.subect, mergeFields),
      // Lava.render(Email.Body, mergeFields)
    ])
      .then(([subject, body]) => {

        let Communication = {
          SenderPersonAliasId: null,
          Status: 3,
          IsBulkCommunication: false,
          Guid: makeNewGuid(),
          Subject: subject,
          MediumData: {
            HtmlMessage: body
          }
        }

        return api.post("Communications", Communication)

      })
      .then((CommunicationId) => {

        if (CommunicationId.statusText) {
          throw new Meteor.Error(CommunicationId)
        }

        // this is a bug in core right now. We can't set Mandrill on the initial
        // post because it locks everything up, we can however, patch it
        api.patch.sync(`Communications/${CommunicationId}`, {
          MediumEntityTypeId: 37 // Mandrill
        })


        if (typeof PersonAliasId === "number") {
          PersonAliasId = [PersonAliasId]
        }


        let ids = []
        for (let id of PersonAliasId) {
          let CommunicationRecipient = {
            PersonAliasId: id,
            CommunicationId,
            Status: 0, // Pending
            Guid: makeNewGuid()
          }

          let CommunicationRecipientId = api.post.sync("CommunicationRecipients", CommunicationRecipient)

          ids.push(CommunicationRecipientId)
        }

        return ids

      })
      .then((communications) => {

        for (let CommunicationRecipientId of communications) {
          if (CommunicationRecipientId.statusText) {
            throw new Meteor.Error(CommunicationRecipientId)
          }
        }

        return communications
      })
      .catch((e) => {
        console.log(e)
        throw e
      })


  }
 static _renderBody(body, metadata) {
   const defaults = { list_name: '' };
   const bodyMetadata = Object.assign({}, defaults, metadata);
   return liquid.parseAndRender(body, bodyMetadata);
 }