Reputation: 3380
I have a list of links which leads to different articles. They look something like this:
<a ui-sref="post-view({ id: post._id })">...</a>
And they produce hrefs like this: href="/blog/546cb8af0c0ec394d7fbfdbf"
, which is what it is supposed to do. When I click the link, I go to the relevant article with the id 546cb8af0c0ec394d7fbfdbf
.
However, I think having the id in the url like that is less userfriendly than having the title of the article, which is what I want. But I can't think of a good way to do it.
Since an articles title not necessarily are unique, I don't know how to get the correct article from the database based on the title (which isn't possible, I need something unique to look it up by).
I've build the site on node, with mongodb, express, and angular. For routing I use the angular ui-router project.
This is how the routing looks in ui.router:
.state('post-view', {
url: '/blog/:id',
templateUrl: '/post',
controller: 'post'
})
As you can see, I use the :id
in the url, which I access in the post
controller.
If I was supposed to show the article on the same page, as a sub state of the currently active state, I could have inherited the id from the parent state, but since this leads to a new page, I'm not sure what I could do.
Does anyone have any experience with this?
Upvotes: 0
Views: 857
Reputation: 714
I recommend you to use a slug. A slug is a URL friendly version of a title,
Title: My Hero Post
Slug: /my-hero-post
Example of WordPress ad some replacement whenever it creates a slug from a title:
Documentation: wp_unique_post_slug
What you need to do is to replace characters like å
or /
in your title with something URL friendly and replace spaces with -
and then save that as a unique key in your post object when you are creating the post. You can also have a look at the ghost source code for an example:
This NPM package actually does most of the work for you: slugify
Upvotes: 2
Reputation: 1346
My recommendation to you is to not use the name of the article in the url if you can not guarantee that the name is unique and will not change or be edit in the future.
Because in this situation you will have to manage all previous names and point them to the correct url with 301 redirect code for SEO purposes and you will also have to convert special characters that can't perform in the URL.
So I take it you do not want to use the _id that Mongodb make for you and you can make your id yourself. start with 1 and check each time what was the last number and increase it by one
Upvotes: 0