Coder Social home page Coder Social logo

grunt-include-replace's Introduction

grunt-include-replace Build Status devDependency Status

Grunt task to include files and replace variables.

Allows for parameterised file includes:

hello.html

<!DOCTYPE html>
<h1>Hello World!</h1>
@@include('/path/to/include/message.html', {"name": "Joe Bloggs"})

message.html

<p>Hello @@name!</p>

Result:

<!DOCTYPE html>
<h1>Hello World!</h1>
<p>Hello Joe Bloggs!</p>

Getting Started

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-include-replace --save-dev

One the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-include-replace');

The "includereplace" task

Overview

The task allows you to preprocess your project file contents by replacing placeholder "variables" and including content from other files. In addition to "global" variables that are replaced in all files you specify, the task introduces the concept of "local" variables, which are passed as parameters to included files.

WARNING: The task does not check for recursive includes.

In your project's Gruntfile, add a section named includereplace to the data object passed into grunt.initConfig().

grunt.initConfig({
  includereplace: {
    your_target: {
      options: {
        // Task-specific options go here.
      },
      // Files to perform replacements and includes with
      src: '*.html',
      // Destination directory to copy files to
      dest: 'dist/'
    }
  }
})

Options

options.globals

Type: Object
Default: {}

Global variables available for replacement in all files.

options.prefix

Type: String
Default: @@

Variable/include directive prefix. Careful when changing as it is added to the regular expression used for finding variables to be replaced.

options.suffix

Type: String
Default: ''

Variable/include directive suffix. Careful when changing as it is added to the regular expression used for finding variables to be replaced.

options.includesDir

Type: String
Default: Relative to including file

Directory where includes will be resolved.

options.docroot

Type: String
Default: .

@@docroot is a magic local variable that contains the relative path from the file that uses it to the path specified.

options.encoding

Type: String
Default: utf-8

Encoding files are using.

options.processIncludeContents

Type: Function
Default: undefined

A function called for every included file prior to processing by grunt-include-replace. It is passed the include file contents, local variables and the file path as parameters and should return the (possibly altered) file contents.

Usage Examples

Default Options

includereplace: {
  dist: {
    options: {
      globals: {
        var1: 'one',
        var2: 'two',
        var3: 'three'
      },
    },
    src: '*.html',
    dest: 'dist/'
  }
}
Files array format
includereplace: {
  dist: {
    options: {
      globals: {
        var1: 'one',
        var2: 'two',
        var3: 'three'
      },
    },
    files: [
      {src: 'js/**/*.js', dest: 'dist/', expand: true, cwd: 'src/'},
      {src: '*.css', dest: 'dist/css/', expand: true, cwd: 'src/css'}
    ]
  }
}
Files object format
includereplace: {
  dist: {
    options: {
      globals: {
        var1: 'one',
        var2: 'two',
        var3: 'three'
      },
    },
    files: {
      'dist/js/': ['**/*.js', '!dist/**/*.js'],
      'dist/css/': ['**/*.css', '!dist/**/*.css']
    }
  }
}

Custom Options

The following example allows include statements to appear as comments in HTML files by altering the prefix and suffix. Also all includes are resolved relative to the directory inc/ (relative to your Gruntfile) rather than relative to including file.

includereplace: {
  dist: {
    options: {
      prefix: '<!-- @@',
      suffix: ' -->',
      includesDir: 'inc/'
    },
    src: '*.html',
    dest: 'dist/'
  }
}

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.

Release History

  • 2016-08-08   v5.0.0   Less verbose output
  • 2016-04-06   v4.0.0   Grunt 1.x support
  • 2015-08-28   v3.2.0   Pass file path to processIncludeContents
  • 2015-08-04   v3.1.0   Support for non-utf8 encoding
  • 2015-02-05   v3.0.0   Better logging for missing source files
  • 2014-05-05   v2.0.0   Adds globbing on include paths
  • 2013-12-30   v1.2.0   Rename like grunt-contrib-copy by specifying dest filename (for single files)
  • 2013-06-19   v1.1.0   Added magic local variable @@docroot: relative path from the file that uses it to the path specified
  • 2013-06-19   v1.0.0   Refactored files processing code to use Grunt files API properly
  • 2013-05-03   v0.4.0   Support for cwd directive
  • 2013-04-26   v0.3.0   Added new option includesDir - if set all includes resolved relative to that directory
  • 2013-04-19   v0.2.0   Added option processIncludeContents - a function that allows you to alter included file contents
  • 2013-02-18   v0.1.0   Grunt 0.4.x support

js-standard-style

grunt-include-replace's People

Contributors

alanshaw avatar builtbylane avatar diogobeda avatar druide avatar dumbccount avatar marlonbernardes avatar monzou avatar orthographic-pedant avatar qyoz avatar timothyklim avatar whispy avatar xhmikosr 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-include-replace's Issues

Messing with indentation in the resulting html

Having this structure in the main work html file:

<!-- @@include('head.html') -->

  <body>
    <!-- @@include('test.html') -->
  </body>

</html>

and this in the include:

<div class="indent1">
  <div class="indent2">
    <span class="indent3"></span>
  </div>
</div>

results in this:

<html>
  <head></head>

  <body>
    <div class="indent1">
  <div class="indent2">
    <span class="indent3"></span>
  </div>
</div>
  </body>

</html>

expected result was:

<html>
  <head></head>

  <body>
    <div class="indent1">
      <div class="indent2">
        <span class="indent3"></span>
      </div>
    </div>
  </body>

</html>

Grunt aborting - Warning: undefined is not a function Use --force to continue

I have the below config in my grunt file however keep getting an error:

Running "includereplace:dist" (includereplace) task
Warning: undefined is not a function� Use --force to continue.

Removing this task from my build works without issue.

Environment:
osx 10.10.3
node v0.12.7
npm 2.14.1

Any ideas??

...
includereplace: {
dist: {
options: {
},
files: [
{
src: 'src/profile/index.html',
dest: 'dist/profile/index.html'
},
{
src: 'src/photos/index.html',
dest: 'dist/photos/index.html'
},
{
src: 'src/admin/index.html',
dest: 'dist/admin/index.html'
},
{
src: 'src/login/index.html',
dest: 'dist/login/index.html'
}
]
}
},
...

requirejs: Using docroot on windows results in windows directory separators in path

Hi! Thanks for your plugin to begin with! :)

As the title says, on windows I'm currently ending up with

@@docrootstyles.css
..\../styles.css

which is only a cosmetic problem for css files as it still gets loaded, but if I use the relative path

..\../

as a basic to include more files with requirejs, it does convert the above path to

..../

Could you include an option to define the directory separator? Or maybe have it solved automatically?

Cheers,
Thomas

How to specify partials?

If I specify src: '*.html', how does the plugin know which files are the real files to be processed vs. partials (files only to be included). For example, Sass puts allows an underscore prefix for partials. Or is there an assumptions that partials reside in a different directory?

Also can I nest includes?

Missing include raw.

There are some template file(contain <%= ... %> syntax) included into the index.html file.
So I want to include raw data.

Chokes on })

When I have }) in a string in the parameter JSON grunt-include-replace fails with

Warning: Unexpected end of input Use --force to continue.

Flatten destination output

Hi,

Is it possible to flatten the output of the files in the dest folder? My templates are nested relative to the grunt file into something like /src/templates/index.html so by declaring

dest: 'dist';

the output is

dist/src/templates/index.html,

where i'd prefer

dist/index.html

Thanks.

Grunt 0.4 Release

I'm posting this issue to let you know that we will be publishing Grunt 0.4 on Monday, February 18th.

If your plugin is not already Grunt 0.4 compatible, would you please consider updating it? For an overview of what's changed, please see our migration guide.

If you'd like to develop against the final version of Grunt before Monday, please specify "grunt": "0.4.0rc8" as a devDependency in your project. After Monday's release, you'll be able to use "grunt": "~0.4.0" to actually publish your plugin. If you depend on any plugins from the grunt-contrib series, please see our list of release candidates for compatible versions. All of these will be updated to final status when Grunt 0.4 is published.

Also, in an effort to reduce duplication of effort and fragmentation in the developer community, could you review the grunt-contrib series of plugins to see if any of your functionality overlaps significantly with them? Grunt-contrib is community maintained with 40+ contributors—we'd love to discuss any additions you'd like to make.

Finally, we're working on a new task format that doesn't depend on Grunt: it's called node-task. Once this is complete, there will be one more conversion, and then we'll never ask you to upgrade your plugins to support our changes again. Until that happens, thanks for bearing with us!

If you have any questions about how to proceed, please respond here, or join us in #grunt on irc.freenode.net.

Thanks, we really appreciate your work!

Argument of include can't have linebreak

Now this is serious trouble for me.

What i mean is that:

@@include('templates/main_heading.tpl.html', {
    "subheader": "Subheader introduction",
})

pass ok

@@include('templates/main_heading.tpl.html', {
    "subheader": "
           Subheader introduction
           test test test
    ",
})

is not!
got:
Warning: Unexpected token
Use --force to continue.

This is superimportant, since you can do stuff like that even:

@@include('templates/main_heading.tpl.html', {
    "content": "
        <h3>thiis is my supadupa haeding</h3>
        <div class='p'>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis.</div>
    ",
})

And everything passes perfectly good except linebreaks :\

I really hope it's fixeable (seem to be regex issue that can be overcome)
If anybody can post solution immideately (before | if at all) it would be fixed with new release i would love to see it)

Destination can't be a file

I've tried and tried but I can't seem to get the dest to be anything but a directory. I'd really like to be able to select a single file, replace a few variables in it, and then output it to a new file in the same directory. I don't want to overwrite the old file so I need to be able to provide a destination file name, however every attempt I've made has resulted in new directories being created instead.

Even the grunt files object method doesn't work:

files: {
    '<% yeoman.appScripts %>/app.min.js': '<% yeoman.appScripts %>/app.js'
}

(Yes, I'm calling my destination file .min.js because I need to call it something different and I plan to minify it immediately afterwards anyways)

Default encoding support

I found that only files whose encoding is UTF-8 can combine to correct ones. Otherwise, it would be garbled in the browser.

Since this is about file operations, encoding support should be considered since grunt has provided grunt.file.defaultEncoding API to support non-utf8 encoding.

Later I will make a pull request to support default encoding if you would like it.

Variable name shows up when not defined

Instead of showing the variable name in the processed page, it would be nice to output nothing when the variable is not defined.

For example, I have a header.html include that gets a @@title variable passed in on all pages except for the home page, but @@title shows up in the title tag since it's not defined.

The workaround is to define it and leave it blank like this: @@include('header.html', {"title": ""}), but it would be easier to leave that out.

Top-level `processIncludeContents` option

Because I need to apply a uniform transformation across both includes and "includers", I locally altered include-replace to optionally apply the processIncludeContents function not only to includes, but also to top-level files.

If this is welcome, I'd like to provide a patch for this.

includereplace: {
  dist: {
    options: {
      processIncludeContents: function (src, locals) {
        // do sthg!
      },
      // if this is thruthy, all levels will be processed with `processIncludeContents`
      processTopLevel: true
    },
    src: '*.html',
    dest: 'dist/'
  }
}

File path

Hi there,

Is it possible to get the file path in the processIncludeContents function for manipulation?

I'm trying to get the dynamic URL in static HTML pages.

Thanks!

Allow undeclared parameters to be defaulted

It would be really useful if you could set any null parameters to a default value. For instance:

snippet.html could contain:

<p>@@one</p>
<p>@@two</p>

And be included via:
@@include("snippet.html", {"one":"text"})

Currently, as nothing is passed in for @@two this will will display:

text
@@two

It would be nice to be able to define a default value for parameters, so any missing parameters can be treated as a blank string by default (or have some default text entered) rather than showing the unused @@ variable in the output.

Renaming Generated files

Allow renames (suffix?) to generated files

possible expected behaviour


includereplace: {
      include: {
        options: {
          // Task-specific options go here.
          includesDir: './',
        },
        src:  ['*.html'],
        dest: 'app/',
        cwd:  'pages/',
        expand: true,
        rename: [{
               match: '.html',
               replacement: '-generated.html'
            }]
      }
    }

Will check for names containing the match pattern and rename them with the replacement string, as would do str.replace(match, replacement)

rename like grunt-contrib-copy?

These produce /bin/src/index.production.html:

files:[ { src:"../src/index.production.html", dest:"../bin/index.html" } ]
src: "../src/index.production.html",
dest: "../bin/index.html",

This produces /bin/src/index.html/index.production.html:

files:[ { cwd:"../src/", src:"index.production.html", dest:"../bin/index.html", expand:true, flatten:true } ]

These produce nothing:

files:{ "../src/index.production.html" : "../bin/index.html" }
files:{ "../src/index.production.html" : ["../bin/index.html"] }

Global issue

Hey, @alanshaw.

I have a project I use grunt-include-replace. My config is

includereplace: {
    dist: {
        options: {
            globals: {
                DATE: '<%= grunt.template.today("dddd, mmmm dS, yyyy, HH:MM:ss Z") %>',
                headHtml: '',
                bottomHtml: '',
                metaDescription: '',
                metaKeywords: ''
            }
        },
        files: [{
            src: ['*.html', '!**/google*.html'],
            dest: '<%= dirs.dest %>/',
            expand: true,
            cwd: '<%= dirs.src %>/'
        }]
    }
},

Everything works fine, except for bottomHtml; it's always empty. Here's how I call it from an HTML file:

@@include("_includes/header.html", {
    "title": "BowPad JavaScript Plugins",
    "headHtml": "<link rel=\"stylesheet\" href=\"/css/prettify.min.css\">",
    "bottomHtml": "<script src=\"/js/prettify/prettify.js\"></script>\n<script>window.onload = prettyPrint();</script>"
})
...

and in my footer.html I have

    @@bottomHtml

</body>
</html>

If I set bottomHtml to anything in Gruntfile globals, then it gets replaced just fine too.

Any ideas?

Variables inside quotes?

Is it possible output variables when inside quotes, e.g. <div class="block @@classes"></div>?

Does not seem to work for me - not sure how to escape quotes.

In search for a flatten option

Hey there,

I am looking to move from grunt-includes to you package but have come across one issue I may not be able to fix.
In grunt-includes you have a flatten option that ignores the folder structure of the processed HTML files and starts with that folder.
That way my folder with unprocessed HTML files can be rendered and go into a PROD folder.

I have my unprocessed files in whatever/folder/index.html
Currently I get PROD/whatever/folder/index.html
What I want is: PROD/index.html

and every respective file with folders so:
My unprocessed files in whatever/folder/sub/index.html
Currently I get PROD/whatever/folder/sub/index.html
What I want is: PROD/sub/index.html

What do you think?

Recursive replace

Hi.

Is there any workaround so that the replace happens recursively? Or can you consider adding such an option?

Thanks.

Output file missing . in name

I am using the following config:

"grunt-include-replace": "~0.3.0"
includereplace: {
  dist: {
    files: {
      'dist/': '*.html'
    }
  }
}

Log shows:

Running "includereplace:dist" (includereplace) task
>> Processed in.html

Done, without errors.

However, the resulting file is

dist/inhtml

The '.' is omitted

Local variables object refering

Any way to refer whole local variables object in included file, to pass it in another include?

This seem to wrok fine:

processIncludeContents: function(contents, localVars) {
    var local = contents.replace(
        /@@local_vars/g,
        JSON.stringify(localVars)
    );
    return local;
},

Can't use `/* @@` and ` */` As prefix and suffix?

Mostly looking for confirmation--Is it true that I can't use JS comments to contain my includes?

Works:

includereplace:
  options:
    prefix: '<!-- @@'
    suffix: ' -->'

Does not work:

includereplace:
  options:
    prefix: '/* @@'
    suffix: ' */'

Is this because those characters are incompatible with the regex used to find the replacement areas?

Wrong dest path

My config

    includereplace: {
        dev: {
            src: 'app/*.html',
            dest: '.tmp/'
        }
    }

When I run grunt includereplace -v, got this

Running "includereplace:dev" (includereplace) task
Verifying property includereplace.dev exists in config...OK
Files: app/404.html, app/about.html, app/admin.html, app/all_day_look.html, app/faq.html, app/how_it_works.html, app/index.html, app/team.html -> .tmp/ ...
Reading app/index.html...OK
Writing .tmp/app/index.html...OK
>> Processed app/index.html

It's writing .tmp/app/index.html but not .tmp/index.html.
How can I make it work as I expected?

Not creating dist directory

Just started to look at this plugin. Looks really useful, except that I am not able to make it work. The includereplace:dist task runs, but the dist directory is not created. Here's my grunt file: what am I doing wrong?

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({

    // Remove the build directory
    clean: {
      clean: ['dist/']
    },

    // Build the site using grunt-include-replace
    includereplace: {
      dist: {
        options: {
          includesDir: 'inc/'
        },
        src: '*.html',
        dest: 'dist/'
      }
    }
  });

  // Load plugins used by this task gruntfile
  grunt.loadNpmTasks('grunt-include-replace');
  grunt.loadNpmTasks('grunt-contrib-clean');

  // Task definitions
  grunt.registerTask('default', ['clean', 'includereplace:dist']);
};

Trouble getting option.prefix and option.suffix to work

Wanted this feature to work with CSS comment before include.

Tried your example option: WORKS

[HTML]

<style>
<!-- @@include('styles.css') -->
</style>

[GRUNTFILE]

options: {
  prefix: '<!-- @@',
  suffix: ' -->',
}

then tried this: DOESN'T WORK

[HTML]

<style>
/* include('styles.css') */
</style>

[GRUNTFILE]

options: {
  prefix: '/* ',
  suffix: ' */',
}

then this, with Regex escapes: DOESN'T WORK

options: {
  prefix: '\/\* ',
  suffix: ' \*\/',
}

Any tips appreciated, thanks.

support Server SSI

Such as:

<!--#include virtual="_header.html"-->

That will be recognised by Server with SSI,such as Nginx、Apache,But grunt-include-replace will not work.could you compatible both?

Keep the indent

Source:

<div>
             @@include('test.html')
</div>

Result:

<div>
Contents of test.html without a original indent
</div>

Warning: Arguments to path.join must be strings

mac 10.8
node v0.10.15
grunt v0.4.1

includereplace: {
      dist: {
        options: {},
        files: [
          {src: 'static-html-dev/*.html', desc: 'static/'},
          {src: 'static-html-dev/settings/*.html', desc: 'static/settings/'},
          {src: 'static-html-dev/user/*.html', desc: 'static/user/'}
        ]
      }
    },

BTW:it is all right when use node v0.8.x

Proposal: Templating with Moustache

First, grunt-include-replace just became one of my favorite Grunt tasks, congrats for such an amazing and convenient work.

It would be really aweome if it could use Mustache templating, kind of what fragment.js does. Being able to process simple loops and conditionals would make this just perfect.

Send parameters through nested includes

I'm trying to send parameters through nested includes but occurs the following error when executing the task: Unexpected token J Use --force to continue.

index.html

@@include('/path/to/include/message.html', {"name": "Joe Bloggs"})

message.html

@@include('/path/to/include/message2.html', {"name": @@name})

message2.html

<p>Hello @@name!</p>

Encoding change

In code encoding is chagne globally for grunt.file. If other task use different encoding it will be overwritten.
In grunt.file functions as second argument we could set object with option encoding. This is better solution than change it globally. Other way is store in local variable grunt.file.defaultEncoding before change it, and restore defalut value at end.

Task default option encoding should be 'utf8' not 'utf-8'

I'd like an example for this use case: If my source file is in a nested folder, put the output directly in that folder instead of in the destination in a nested directory

For example, if my file system looks like this:

Gruntfile.js
src/dir/dir2/myhtml.html
dist

If my configuration says this:

        includereplace: {
            taskname: {
                options: {

                },
                src: "src/dir/dir2/myhtml.html",
                dest: "dist"
            }
        }

It ends up putting myhtml.html in a directory like this:

dist/dir/dir2/myhtml.html

I want it to put it in a directory like this:

dist/myhtml.html

I can't figure out any way to accomplish this.

access to local variables

If no local variables are passed to processIncludeContents() I would like to use default values. Can I somehow define new local variables for the replace operation in the processIncludeContents function?

Multitask not working, not compiling

I'm trying to add includereplace, to a multitask, but it simply doesn't works, it do nothing...

Can you check if the task runs with multitask?

includereplace : {
development : {
                files : [
                    {
                        cwd : 'src/',
                        src: ['*.html', 'pages/*.html'],
                        dest : '<%= dirs.devput %>',
                        expand : true
                    }
                ]
            },
}
grunt.registerMultiTask('build','Builds the app according to the environment',function(){
        var env = this.target;
        var outputDirs = {
            development:'dev',
            production:'dist'
        };

        grunt.config('dirs.output',outputDirs[env]);
        grunt.task.run('jshint');
        grunt.task.run('less:'+env);
        grunt.task.run('includereplace:' + env);
        grunt.task.run('concat:'+env);
        grunt.task.run('uglify:'+env);
        grunt.task.run('copy');
        grunt.task.run('clean');
    });

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.