1

I have 2 issues that I need help with:

  1. I want to load ENTRIES from any section where the first URL segment of the entry matches jobs.

  2. I am using the code below to load any SECTION where the first URL segment matches jobs. This code works to load the sections. I'm just wondering if there's a more efficient way to write this to load the sections. This is separate from loading the entries. I need to do both.

    {% set allSections = craft.sections.getAllSections() %}
    
    {% for section in allSections %}
    
    {% set sectionURL = section.getUrlFormat()|split('/')[0] %}
    
    {% if sectionURL == "jobs" %}
        {{ section.name }}
    {% endif %}
    
    {% endfor %}
    
  • Just to be clear, that code is working for you and you're just wondering if there is a more efficient way? – Brad Bell Feb 14 '17 at 19:42
  • I want to know how to get entries where the 1St url segment matches jobs. That code is working to get the sections with the 1st URL segment jobs. I am also wondering if there is a more efficient way to get the sections. – triplethreat23 Feb 15 '17 at 3:13
2

To check if the word jobs is in the sectionUrl you can use twig's matches to create a regular expression that looks for jobs

{% set allSections = craft.sections.getAllSections() %}
{% for section in allSections %}
    {% set sectionURL = section.getUrlFormat()|split('/')[0] %}

    {% if sectionURL matches "/jobs/" %}
        {{ section.name }}
    {% endif %}

{% endfor %}
  • This works, is there an advantage to using {% if sectionURL matches "/jobs/" %} vs. {% if sectionURL == "jobs" %}? – triplethreat23 Feb 16 '17 at 18:48
  • @triplethreat23 matches will match any string that contains jobs e.g /a-jobs-list/ and using == matches a string that is only jobs. If you're looking to find a string that contains the string jobs then matches would be what you're after but if you're looking for a specific string then == would be appropriate – Pindo Feb 17 '17 at 4:09
1

If I understand you right all you need is:

{% for section in allSections if craft.request.getFirstSegment() == 'jobs' %}

 {# other code here #}

{% endfor %}

You can give conditions to your for loop which saves you another if statement. You also dont need to split any url because craft already got Segment selection which is found here: https://craftcms.com/docs/templating/craft.request/

  • This code seems to return all sections. – triplethreat23 Feb 16 '17 at 18:45

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.