Home > other >  href link to current path's child
href link to current path's child

Time:08-19

I'm trying to link from page http://example.com/en/blog to http://example.com/en/blog/article-1337

I want to keep the /blog part of the path and suffix it with the next page article-1337.

Example:

<!-- http://example.com/en/blog -->
<h1>Blog posts</h1>
<a href="/my-dog-is-4">My dog is now 4 years old</a>
<a href="/mom-left-me">Mother left me at Disney land</a>
<!-- Clicking the links above should ideally navigate to http://example.com/en/blog/my-dog-is-4 -->

In the HTML I've tried the following:

<a href="article-1337"> - Links to http://localhost:3000/en/article-1337
<a href="/article-1337"> - Links to http://localhost:3000/article-1337
<a href="./article-1337"> - Links to http://localhost:3000/en/article-1337
<a href="../article-1337"> - Links to http://localhost:3000/article-1337

Is it possible to link a page like this to include the current path article-1337 without JS?

I could do the following, but it feels dirty:

<a href={window.location.pathname.split('/').pop()   '/article-1337'}>

The reason I want to do this is because blog will be different depending on locale, but I want to avoid adding translations to the href attribute.

CodePudding user response:

You will need to link to blog/article-1337:

<a href="blog/article-1337">…

Getting the blog/ part is not possible by means of HTML alone.

Using JavaScript, as you mention, is dirty for a static HTML page because it’s relying on client-side scripting for the very foundation of site navigation.

The reason why this is complicated is due to your choice of URL architecture. Would you use /en/blog/ as the home for the blog, simply linking to article-1337 would work.

Your folder hierarchy would be

/en/index.html
/en/blog/index.html
/en/blog/article-1337.html

But, you certainly have some generator for your HTML, you are not writing everything by hand.

So this generator handles also navigation and marking the current page as active in the navigation. It is also able to insert the current path into HTML.

For example, in PHP you could use

<a href="<?= $_SERVER['REQUEST_URI'] ?>/article-1337">
  • Related