1

I'm trying to set up a site for clients that have locations in multiple cities and who want to be able to display something specific to that location on certain pages. I would like to set up routes using the city name as a variable, followed by the page (i.e. mysite.com/chicago/pricing, mysite.com/boston/pricing, etc.), and have it route to the same section and template with all of that section's corresponding entry fields.

I was planning to grab the URL parameter as a variable that enables me to dynamically load content based on a simple string match for that variable. I want to do something like this

{% set location = matches[1] %}

{% if not location %}
  {% set selectedLocation = locations.defaultLocation %}
{% else %}
  {% set selectedLocation = location %}
{% endif %}

....

{% for plan in entry.pricingPlans %}
    {% if plan.location == selectedLocation %}
      ...
    {% endif %}
{% endfor %}

I can route to the template itself just fine, but I don't get the data. Any suggestions on how best to achieve this? I'm not very PHP savvy and have only recently started getting to more advanced tasks in Craft.

GMStevens
  • 13
  • 2

1 Answers1

1

Is the problem you're not getting the segment from the URL?

{% set locationSlugInUrl = craft.request.getSegment(1) %} or {% set locationSlugInUrl = craft.request.firstSegment %} should do that for you.

Or you're not getting the entry? In which case you need to either specify the template in that section's settings or do something like {% set entry = craft.entries.section('pricing').first %} or whatever the section slug is (assuming it's a single).

And what kind of field is entry.pricingPlans? If it is a matrix field, what type of field is plan.location?

Clive Portman
  • 2,908
  • 17
  • 36
  • I was able to figure this out by using something like {% set entry = craft.entries.section('pricing').first %} if entry was null, that way I can handle cases where a user goes to mysite.com/pricing (where the section is passing the entry data) or mysite.com/boston/pricing (where I need to pull from craft.entries.section). Thanks. – GMStevens Jun 01 '17 at 15:11
  • Yep, sounds familiar. – Clive Portman Jun 02 '17 at 08:15