So what I'd like is:

If URI would look like {username}, load _thisTemplate.

Couldn't find the way without solid point like author ID.

  • Had the same issue, had to work around like: /people/phil-collins/832 ...
    – tom
    Jun 1 '15 at 12:53
  • One of the options, yes. I doubt, that it is possible yet. The craft needs to know, what user is the click link to and without assigning an user's ID, I think it's impossible. Jun 1 '15 at 15:31

I would not particularly advise creating a uri pattern that was just 'www.site.com/username' because usernames can essentially be anything which might cause routing conflicts (i.e. if the username is 'index' for example). You could however use something like 'www.site.com/members/username' or 'www.site.com/u/username'.

One way to do this would be to add a route using a 'subpattern'. For more info check out the routing docs on accessing subpatterns in your templates.

Here is the example given in the docs, which provides the variables 'year' and 'month' to the template that correspond to the matched uri segments (i.e. `news/2015/02'):

'news/(?P<year>\d{4})/(?P<month>\d{2})' => 'news/_archive',

You could essentially do the same thing but with a 'username' variable.

'u/(?P<username>[^\/]+)' => '_thisTemplate',

You can then use the 'username' variable in your template to retrieve the corresponding user.

{% set user = craft.users.username(username).first() %}
{% if user %}
    {{ user.firstName }}
{% else %}
    {% redirect 404 %}
{% endif %}
  • 1
    Note that by {% set user %} you're overwriting Craft's global user variable (i.e. the currently logged in user). Not a problem in most cases, but probably worth mentioning. Jun 1 '15 at 18:06
  • 2
    @mmikkel Good point. Although, 'currentUser' would still refer correctly to the currently logged in user, which I believe is the recommended usage anyway. Jun 1 '15 at 18:14
  • To match everything but a slash for a URL pattern use this regular expression: (?P<username>[^\/]+)
    – carlcs
    Jun 1 '15 at 20:30
  • Thanks for the addition @carlcs. You also made me realize that I had an error in my expression, which was still expecting 4 digits. Corrected. Jun 1 '15 at 21:37
  • 1
    Yes. The link you posted in your comment looks correct. As for the extra character, the pound sign "#", as you probably know, is reserved for anchor tag links — so I would suggest using something else at a minimum, perhaps dash "-" or underscore "_". Although the best in my opinion is still a subpath such as "/u/username". Jun 2 '15 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.