Search code examples
javascriptpermalinkshandlebars.jsmetalsmith

How do I use metalsmith-permalinks in a Handlebars template


I have collections set up and working properly.

I am looping through a collection of projects

{{#each collections.projects}}
    <a href="" class="portfolio-entry">

        <div class="info-frame portfolio-title">
            <h4>{{this.title}}</h4>
        </div>

        <div class="info-bits centerContext">
            <ul class="centerElement">
                <li class="info-bit">{{this.skills}}</li>
                <li class="info-bit">{{this.type}}</li>
                <li class="info-bit">{{this.platform}}</li>
            </ul>
        </div>

        <div class="project-thumbnail">
            <img src="{{this.thumbnail}}" alt="">
        </div>

    </a>
{{/each}}

I would like to use metalsmith-permalinks in order to resolve each link's url

I tried all kinds of lame things like this

<a href="{{this.permalink}}" class="portfolio-entry">

and this

<a href="{{this.url}}" class="portfolio-entry">

Of course - none of them works.

I struggled to find any detailed information on how to actually use permalinks within your template anywhere online.


Solution

  • The permalinks plugin adds path metadata property that doesn't seem to be documented well. This should be what you need to achieve links.

    The Github page notes:

    If no pattern is provided, the files won't be remapped, but the path metadata key will still be set, so that you can use it for outputting links to files in the template.

    I haven't found anywhere else showing the use of this but I'd assume the above quote means that it is standard behaviour.

    You can use it like:

    {{#each collections.projects}}
        <a href="/{{this.path}}/" class="portfolio-entry">
    

    The first / is so that it resolves to the current host and the trailing / is optional (depending on your http server configuration.