I am building a site for a travel agency. Each agent needs to have his/her own public profile page. I want each agent's profile page to be accessed at agencyname.com/agentname, with agentname being the agent's username. This would load an agent profile template populated with the given agent's profile data.

I still need other non-agent segment-1 pages to continue working also, like agencyname.com/cruises or agencyname.com/group-travel. These would be 'normal' template pages.

Is there any way to make this work dynamically? Creating a dynamic route with only a token in Segment 1 breaks access to other regular pages. I don't want to have to create a hard route every time we add an agent, and we don't want to add another segment like agencyname.com/agent/agentname. We want the URL each agent puts on their business card to be as clean and easy to remember as possible.

I'm thinking something along the lines of this logic:

If Segment 1 matches a username
   Display the profile template for that user
   Continue routing per the normal routing checks

I don't have the knowledge to build a plugin, or the budget for someone else to. I'm seeking solutions that could be implemented without a plugin (unless there's already a plugin available).

Any constructive thoughts are appreciated.


You could add a check at the top of all of your templates that tests if the first uri segment matches one the agent names.

{% set firstSegment = craft.request.firstSegment %}
{% set agents = craft.users.group('agents') %}
{% for agent in agents %}
    {% set agentName = agent.firstName ~ "-" ~ agent.lastName %}
    {% if firstSegment == agentName %}
        {% set requestedAgent = agent %}
    {% endif %}
{% endfor %}

{% if requestedAgent is defined %}
    {% include 'users/_profile' with { user: requestedAgent } only %}
{% else %}
    {% extend 'layouts/_main' %}

    ... normal page template goes here

{% endif %}

In your profile template you should now have a variable 'user' available with the requested agent.

{% block content %}
    <h1>{% user.firstName %} {% user.lastName %}</h1>
{% endblock %}
  • That worked well. Here's what I ended up doing. {% set aname = craft.request.firstSegment %} {% if aname %} {% set agentObj = craft.users.username(aname).search('publicProfile:1').last() %} {% if agentObj | length %}{% redirect 'agent/' ~ agentObj.username | lower %} {% endif %} {% endif %} Feb 4 '17 at 19:18
  • I really hate that you can't format code in comments. Feb 4 '17 at 19:19

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.