Easily find the relative path to the root directory in your Metalsmith templates.
Switch branches/tags
Clone or download
Latest commit a649c67 Dec 2, 2016
Failed to load latest commit information.
test add reorder test files Jun 5, 2016
.editorconfig 1.0.0 Jul 4, 2016
.gitattributes 1.0.0 Jul 4, 2016
.gitignore add reorder test files Jun 5, 2016
.travis.yml bump patch Jul 4, 2016
index.js 1.0.0 Jul 4, 2016
license 1.0.0 Jul 4, 2016
package.json bump patch Jul 5, 2016
readme.md tweaks Dec 2, 2016



Easily find the relative path to the root directory in your Metalsmith templates.

Makes relative-to-root links a breeze!

Build Status

Note: metalsmith-rootpath must run after any plugins that move files around, or create new files in your metalsmith build chain (like metalsmith-permalinks, for example). This is because metalsmith-rootpath needs to know what your final output directory will look like before it can assign a correct rootPath value.


$ npm install --save metalsmith-rootpath


var rootPath = require('metalsmith-rootpath');

  .build(function(err) {
    if (err) throw err;

😎 Now all the files and templates in your Metalsmith build have a rootPath variable assigned to them! I am using the handlebars template language in the examples below, but you can use your template language of choice, or access the rootPath value from the file's metadata anyway you like.


Let's assume you have a directory structure like this:

β”œβ”€β”€ index.html
β”œβ”€β”¬ dir1  
β”‚ └── index.html
β”œβ”€β”¬ dir2  
β”‚ └─┬ foo
β”‚   └── index.html
└─┬ dir3  
  └─┬ foo
    └─┬ bar
      └─┬ baz
        └── index.html

The rootPath value in each index.html file would be:

File rootPath
index.html ""
dir1/index.html "../"
dir2/foo/index.html "../../"
dir3/foo/bar/baz/index.html "../../../../"

Relative Links

Use the rootPath variable anywhere you want to grab static files relative to your directory. rootPath will find the root folder no matter how many levels deep your templates are.

For example, if the following line of markup were placed in dir3/foo/bar/baz/index.html:

<link src="{{rootPath}}css/main.css" type="text/css" />

It would result in the following output:

<link src="../../../../css/main.css" type="text/css" />

Relative Navigation

The rootPath variable is useful when building a relative navigation structure, for example, in your Handlebars template partials/navigation.hbs

    <li><a href="{{rootPath}}about/">About Us</a></li>
    <li><a href="{{rootPath}}awesome-page/">Awesome Page</a></li>
    <li><a href="{{rootPath}}contact/">Contact Us</a></li>


MIT @ Michael Wuergler