18

I'm running some checks to see if there is a user logged in, and if that user is someone specific. When accessing user.isCurrent it's returning 1 when I'm logged in, but returns null when I'm not. Should this be returning 0 or false in that case, or should I be checking {% if user.isCurrent is defined %} ?

Lindsey D
  • 23,974
  • 5
  • 53
  • 110
Bill Columbia
  • 896
  • 1
  • 8
  • 18

1 Answers1

29

To determine if the user is logged in at all, you'll want to use the currentUser variable:

{% if currentUser %}
    Welcome, {{ currentUser.friendlyName }}!
{% endif %}

To determine if the logged in user is a specific user, then simply compare against their username:

{% if currentUser and currentUser.username is 'johndoe' %}
    Hey Johnny Boy!
{% endif %}

The isCurrent method is useful when targeting a more generic UserModel (where you don't know if the user would be the current user).

{% for user in craft.users %}
    {% if user.isCurrent %}
        {{ user.friendlyName }} is you!
    {% else %}
        {{ user.friendlyName }} is someone else.
    {% endif %}
{% endfor %}
Lindsey D
  • 23,974
  • 5
  • 53
  • 110
  • This works great thanks for clarifying. I did have an issue with using is in this context though: Unexpected token "string" of value "bill" ("name" expected) I swapped is with == and it seems to working fine now. Maybe some kind of typecast comparison issue? – Bill Columbia Jun 20 '14 at 18:21
  • Huh, interesting... I wonder if it's just a grouping issue. Perhaps put parenthesis around the second part and try it as if currentUser and (currentUser.username is 'johndoe'). In theory, is should be parsed exactly the same as ==. http://twig.sensiolabs.org/doc/templates.html#test-operator – Lindsey D Jun 20 '14 at 18:29
  • Here's another question addressing the topic of is vs is same as vs == vs === ... http://craftcms.stackexchange.com/questions/218/when-to-use-is-same-as-and-when-to-use – Lindsey D Jun 20 '14 at 18:34
  • 1
    @BillColumbia I just bumped into that same issue on a site I'm working on (is vs ==), so I did a little more digging. It looks like is represents a "test operator"... meaning, it runs tests. Meanwhile, == is a "comparison operator". So, I learned something new today... is does not directly translate to == – Lindsey D Jun 21 '14 at 00:50