1

I'm having a difficult time with what seems like a fairly straightforward problem:

I'm listing businesses and their related hours of operation (days/times). I'd like to set up a conditional statement that checks if a Matrix field has content—if so, display hours. If not, display message. My code is as follows:

{% if entry.hours.block('days')|length %} <!-- I am trying to check Matrix field "days" is empty (content exists) -->
<div class="entry__hours">
  <table>
    <tbody>
      {% for block in entry.hours %}<!-- Loop through days/times...this part works fine -->
      <tr>
        <td class="entry__days">{{ block.days }}</td>
        <td class="entry__times">{{ block.times }}</td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>
{% else %} <!-- This part does not show up if Matrix field "days" is empty -->
  <p>We're still trying to track down hours.</p>
{% endif %}

I've also attached a screenshot of my Matrix setup. Thanks so much in advance![enter image description here]1

3

I'm assuming your matrix field is not called hours? Because in your current code you are handeling it like it is.

I think this should work

   {% for block in entry.matrixfieldHandle %}
       {% if block|length %}
           {{block.days}} - {{block.time}}
       {% else %}
           <p>Do something else</p>
       {% endif% }
    {% endfor %}

In your code you want to loop over all the different entries (blocks) within the matrix. If you want to add other types you can easely check for hours like so:

{% if block.type == "hours" %}
   do stuff
{% elseif block.type == "anotherblocktype" %}
   ...

However. Since you only use one type of content I'm not sure if a matrix is the best solution. You could easely put this in a table or supertable .

Then you could just do

{% for row in entry.tableHandle %}
   {% if row|length %}
       {{row.text}}
   {% else % }
       <p>Fallback</p>
{% endif %}

Another option is to check this little plugin: Store hours

| improve this answer | |
  • Thanks so much Jan! Your suggestions worked like a charm—however, you're correct that a matrix was not the best solution. I'd simply gotten so used to using it, I forgot about all my other options. A table worked great and simplified things quite a bit. Thanks again! – Adam Jan 24 '17 at 4:47
  • You can always mark my answer as correct @Adam ;-) – Jan_dh Jan 24 '17 at 8:06

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.