Giter Club home page Giter Club logo

soynode's Introduction

soynode

Build Status

Utility for working with Closure Templates, aka Soy, from within a node.js application. Supports dynamic recompilation and loading for fast iteration during development.

Installing

Either:

  1. Fork, clone or download the source from GitHub, or
  2. Install via NPM using npm install soynode

Usage

var soynode = require('../lib/soynode')

soynode.setOptions({
    outputDir: '/tmp/soynode-example'
  , allowDynamicRecompile: true
})

soynode.compileTemplates(__dirname, function (err) {
  if (err) throw err
  // Templates are now ready to use.
  console.log(soynode.render('example.message.hello', {
      name: process.env.USER
    , date: new Date().toLocaleTimeString()
  }))
})

Also, see examples/example.js.

soynode.get(templatename) - Returns a JS function corresponding to the template name.

soynode.render(templatename, data) - Returns a string that results from executing a template.

soynode.setOptions(opts) - Change the options, see section below.

soynode.compileTemplates(dir, callback) - Compiles and loads all .soy files in the directory.

soynode.compileTemplateFiles(files, callback) - Compiles and loads all .soy files.

soynode.loadCompiledTemplates(dir, callback) - Loads already compiled templates.

soynode.loadCompiledTemplateFiles(files, callback) - Loads already compiled templates.

Where "template name" is referred to, it means the namespace + template name as defined in the Soy file, and the full JS name that the Soy Compiler generates, for example project.section.screen. See the Hello World JS doc on the Closure site for more background.

Options

Options can be set via soynode.setOptions(options). Most of these mirror the command-line arguments for SoyToJsSrcCompiler. The keys can contain the following:

  • tmpDir {string} Path to a directory where temporary files will be written during compilation. {Deprecated: use outputDir} [Default: /tmp/soynode]
  • inputDir {string} Optional path to a directory where files will be read. When compiled from a directory, this option will be overwritten with the caller inputDir. [Default: process.cwd()]
  • outputDir {string} Path to a directory where files will be written. [Default: null]
  • uniqueDir {boolean} Determines whether the compiled files will be placed in a unique directory. [Default: true]
  • allowDynamicRecompile {boolean} Whether to watch for changes to the templates. [Default: false]
  • loadCompiledTemplates {boolean} Whether or not to load the compiled templates. Relevant when you only need to build templates. [Default: true]
  • eraseTemporaryFiles {boolean} Whether to erase temporary files after a compilation. This option does nothing if allowDynamicRecompile is on, because allowDynamicRecompile reuses the files. [Default: false]
  • concatOutput {boolean} Whether the compiled soy.js files should be joined into a single file. This is helpful for loading templates in a browser and simplest to use when outputDir is explicitly set and uniqueDir is false. [Default: false]
  • concatFileName {string} File name used for concatenated files, only relevant when concatOutput is true, ".soy.concat.js" is appended, so don't include ".js" yourself. [Default: compiled]
  • locales {Array.} List of locales to translate the templates to.
  • messageFilePathFormat {string} Path to the translation file to use, which can contain any of the placeholders allowed on the --messageFilePathFormat option of SoyToJsSrcCompiler.jar.
  • cssHandlingScheme {string} Processing options for the css command. More info
  • useClosureStyle {boolean} Whether or not to use goog.provide and goog.require for JS functions and Soy namespaces.
  • shouldGenerateJsdoc {boolean} Whether or not to generate JSDoc on each template function, with type info for the Closure Compiler. More info
  • shouldProvideRequireSoyNamespaces {boolean} Use this option to enable usage with Closure Library. More info
  • shouldProvideRequireJsFunctions {boolean} Use this option to enable usage with Closure Library. More info
  • precompiledDir {string} A directory of precompiled soy.js files. Soynode will check these first and use them if available. You can set this to the same value as outputDir to re-use results from previous runs.

NOTE: Options should be set before templates are loaded or compiled.

Internationalizion

To take advantage of soy's translation features through soynode, you should set the locales and messageFilePathFormat options, like in the example below:

var soynode = require('../lib/soynode')

soynode.setOptions({
    locales: ['pt-BR', 'es'],
    messageFilePathFormat: '/tmp/soynode-example/translations.xlf',
    outputDir: '/tmp/soynode-example'
})

soynode.compileTemplates(__dirname, function (err) {
  if (err) throw err
  // Templates are now ready to use, render specifying the desired locale.
  console.log(soynode.render('example.message.hello', {}, {}, 'pt-BR'))
  console.log(soynode.render('example.message.hello', {}, {}, 'es'))
})

Implementation Notes

The templates are loaded using Node's VM Module. This allows us to execute the generated .soy.js files as is without a post processing step and without leaking the template functions into the global scope.

Calling soynode.get executes code which returns a reference to the template function within the VM Context. The reference is cached, providing a 10x speed up over fetching the template function each time, or evaluating it in place and returning the template output over the VM boundary.

Contributing

Questions, comments, bug reports, and pull requests are all welcome. Submit them at the project on GitHub.

Bug reports that include steps-to-reproduce (including code) are the best. Even better, make them in the form of pull requests.

Author

Dan Pupius (personal website), supported by The Obvious Corporation.

License

Copyright 2012 The Obvious Corporation.

Licensed under the Apache License, Version 2.0. See the top-level file LICENSE.txt and (http://www.apache.org/licenses/LICENSE-2.0).

soynode's People

Contributors

bobbor avatar davidbyttow avatar eduardolundgren avatar evansolomon avatar fat avatar jaidenashmore avatar kaworru avatar mairatma avatar mathieuturcotte avatar mattwhelan avatar nicks avatar valueof avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

soynode's Issues

I would like to be able to access soynode compiled templates on the client side

At the moment the compiled templates are stored in the tmpDir, with a timestamp created before the directory. As I want to be able to compile soy templates and use them on the client side this timestamp disallows access to that file. There should be some way to define a target or output directory so that I can place the .soy.js files for my web pages to request those files.

Option to configure path to soy jar?

The jar file used to compile soy references your closure-templates module, but this doesn't work if individuals need to reference a particular version of the soy jar for compilation. If there was an option (via setOptions) for the location of the soy jar, the closure-templates version could be the default.

loadCompiledTemplates with closure style soy.js files

Could you please provide an example of how to use soynode.loadCompiledTemplates() with pre-compiled .soy.js files?

My .soy.js files look like this, and soynode throws Fatal error: Object [object Object] has no method 'provide'

goog.provide('demo.soy');

goog.require('soy');
goog.require('soydata');

/**
 * @param {Object.<string, *>=} opt_data
 * @param {(null|undefined)=} opt_ignored
 * @return {string}
 * @notypecheck
 */
demo.soy.helloWorld = function(opt_data, opt_ignored) {
  return '<div>hello ' + ((opt_data.name) ? opt_data.name : 'world') + '</div>';
};

protoFileDescriptors support's documentation

Hi!

Based on what I could find out in your source-code, soynode has support for soy's --protoFileDescriptors option, but I couldn't find it documented.

It would be great to have at least a mention of this badass feature, and have more people using it.

I'm more than happy to pimp the docs, if that's something desirable by the core maintainers as a contribution.

Where is the closure-templates repository?

This project depends on the closure-templates module, however npm's github link to that is dead. Is this project dead? I'm getting cryptic errors I can't fix:

soynode: emit error Error {
  message: 'Assertion failed: expected param description3 of type string|goog.soy.data.SanitizedContent, but got undefined.',
  reportErrorToServer: true,
  messagePattern: 'Assertion failed: expected param description3 of type string|goog.soy.data.SanitizedContent, but got undefined.'
}

Relative path to assets

At work I inherited a JavaScript templating project which is built using Google Closure Templates and I am trying to convert it into a CI/CD project, make it open and let others use it and contribute to it.

Background

The project was created so that web applications and sites that use our template just have to point to a server setup as a CDN that hosted our files.

Issue

All our paths were set with an .environment template with if conditions for different servers our files reside on.

/**
 * @param cdnEnv Used to switch between qat, dev, and prod implementations.
 */
{template .environment}
/**{@param cdnEnv}*/
{if $cdnEnv=='qat'}
   https://qat.domain.com
{elseif $cdnEnv=='dev'}
   https://dev.domain.com
{else}
   https://domain.com{/if}/ourfiles/
{/if}
{/template}

Then we call it in the different templates to access our resource files (css, js, images, etc...)

<link rel="stylesheet" href='{call .environment data="all" /}css/theme.css'>

I want our templates to work no matter where we host the files, but if I change the paths to relative to the JS, once it gets injected in the page, it becomes relative to the page itself and breaks.

Is there a way to achieve this?

Link to project: https://github.com/wet-boew/cdts-sgdc

Link to open issue: google/closure-templates#200

Add option for using the shouldDeclareTopLevelNamespaces flag

There's currently no way to use the --shouldDeclareTopLevelNamespaces flag on the compiler through soynode, since there's no option for it. It would be great to have that option.

I have this working on a local branch of mine, so I'll send a pull request with it soon.

Unsupported major.minor version 51.0

soynode: Compile error
java.lang.UnsupportedClassVersionError: com/google/template/soy/SoyToJsSrcCompi
ler : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:14
1)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: com.google.template.soy.SoyToJsSrcCompiler. Prog
ram will exit.
Exception in thread "main"

Add option for custom closure template jar path

I would like to use the newest version of closure templates in my project. However, since closure-templates hasn't been published in quite some time and the path to the jar file is hardcoded I can't.

It would be great to have an option for a custom path to a jar file so that I have more control over what version is being used.

Template commands nested in {literal} ... {/literal} are still parsed.

According to Closure documentation all text within {literal} blocks should not be parsed, including template commands.

{namespace test}

/**
 *
 */
{template .render}
	<div>
		{literal}
			{template .snippet}
				<span>Code snippet.</span>
			{/template}
		{/literal}
	</div>
{/template}

When attempting to render this template, the following error is thrown.

soynode: Compile error
 In file test.soy, template test.render: Lexical error at line 12, column 25.  Encountered: <EOF> after : ""
In file test.soy:12:17: parse error at '{': expected eof, {deltemplate, or {template
		{/literal}
                ^

soynode: Error: Error compiling templates
    at ChildProcess.onExit (/Projects/temp/node_modules/soynode/lib/SoyCompiler.js:308:25)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
soynode: emit error Error: Error compiling templates
    at ChildProcess.onExit (/Projects/temp/node_modules/soynode/lib/SoyCompiler.js:308:25)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)

A similar error is thrown if {namespace name} is included inside the {literal} tags.

Add option for using the isUsingIjData flag

This is similar to #38, but related to the --isUsingIjData flag right now. There's currently no way to it on the compiler through soynode, since there's no option for it.

Missing flags like this make me think that maybe soynode could instead have an easy way to pass flags, without having to have an option for each of them. That would probably mean a bigger change though, just thought it'd be good to mention.

So for now I have this working with an extra option on a local branch of mine, I'll send a pull request with it soon.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.