2

Similarly to how Craft knows that a category is defined when a category slug is used, is there a way to detect a user in the same way?

{% if category is defined %}
...
{% endif %}

Something along the lines of (which only returns true if a user is logged in):

{% if user is defined %}
...
{% endif %}

If a username is in the URL, would/should above code return true similarly to how {% if category is defined %} returns true if a category slug is in the URL? (i.e. .com/news/sherlock_holmes)

I'm able to return author posts using method listed in this question, I'm just trying to simplify even further and have one template list all these views.

1 Answer 1

2

If you're looking for the current (logged in) user, you should use the global variable currentUser.

{% if currentUser %}
    {# currentUser returns a User Model if there is one, so do with it whatever you like #}
{% endif %}

However, if you want to find a user through a URL segment, you might want to get into using routes. If you use advanced routing, you can get what (I think) you want by adding following to your craft/config/routes.php:

return array(
    '(?P<category>[^/\]+)/(?P<user>[^/\]+)/' => 'path/to/template',
)

In your template, you can then use the variables {{ category }} and {{ user }}. Don't hang me on the RegExp-pattern, this is not tested but should get you further.

3
  • I'm looking to relate authored entries based on a username in the URL (i.e. .com/news/sherlock_holmes) without being logged in and without saving segment 1 to a variable first.
    – Ryan Shrum
    Commented Jul 16, 2014 at 20:51
  • Why don't you want to save the segment? Commented Jul 17, 2014 at 13:54
  • Because the segment can be a category or tag as well (in this particular case). Really I'm just wondering, and seems to be not possible currently, if the conditional for user in my question will return true similarly to the category conditional when it exists in the URL.
    – Ryan Shrum
    Commented Jul 18, 2014 at 13:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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