Reputation: 33
I'm making a website with Metalsmith that is templated with Handlebars.
I made an archive page named /articles/index.html, which takes all the articles in /articles/ and lists them chronologically, but when I follow a link in the archive page it takes me to /articles/articles/example-post.html instead of /articles/example-post.html. How do I make it take me to the absolute version of the URL instead a relative version?
The Handlebars script I used to generate the archive is:
{{#if archive}}
<ul>
{{#each collections.article}}
<li><a href={{path}}>{{date}} - {{title}} {{description}}</a></li>
{{/each}}
</ul>
{{/if}}
The {{path}} metadata is generated automatically by Metalsmith. When I call console.log on my generated files, I get an output like:
'/articles/example-post/index.html':
{ title: 'Example Post',
...
path: 'articles/example-post'
...
}
I have an almost identical setup on my homepage that works exactly like it should. Any idea how to get this running in sub-folders?
Edit: Ok, I should be clear: I realize that {{path}} is a relative link, rather than an absolute one. My question should be: "How do I get this to work correctly when I only have {{path}} to work with and it's relative? Is there another variable I should be able to access that would produce the correct link or is there a way to edit {{path}} so that it points to the correct files? As far as I've been able to find, there's no way to edit a variable in Handlebars so I can't append a '/' onto my link or strip the leading 'article/'.
Upvotes: 3
Views: 2147
Reputation: 33
Ultimately, I ended up using metalsmith-paths in my build which adds an array of paths to file's metadata including an "href" path, which is basically what I was looking for.
Ultimately, my script ended up looking like:
{{#if archive}}
<ul>
{{#each collections.article}}
<li><a href={{paths.href}}>{{date}} - {{title}} - {{description}}</a></li>
{{/each}}
</ul>
{{/if}}
So, yeah, the links I was using were just wrong.
If you happen to need to "fix" a link in Handlebars directly like I thought I might, I'm still not sure what to tell you, but it probably involves helpers if it's possible.
Upvotes: 0
Reputation: 3820
Generally, it is better to use relative url instead of absolute url, so your app is not bound to that application env.
But if you need to use absolute, you can use /path/to/somewhere
instead of path/to/somewhere
The reason it is working for your homepage BUT not your other pages is that when you are at the homepage, there is no difference between your relative path and absolute path. So /location/path
and location/path
are the same when you are at the root.
Here is another option to put a /
to the front:
<a href="/posts/{{../permalink}}#{{id}}">{{title}}</a>
Upvotes: 3