2

I know I have come across this before but the solution is escaping me. I have a template and a channel lets call it widgets. If I go to the URL /widgets/ I want it to show all the entries of channel="widget" no problem. Now if i have a url of widgets/a-black-widget then I want to show just the specific info for just a-black-widget. Again no problem. The issue happens when I want to redirect someone who enters a url of /widgets/nonesensevalue meaning an entry that doesnt exist. HEre is my code.

{if segment_2==""}
  {exp:channel:entries channel="{segment_1}" limit="8"}
    <!--Code showing article list-->
  {/exp:channel:entries}
{/if}
{if segment_2!=""}
  {exp:channel:entries channel="{segment_1}" limit="1" require_entry="yes"}
    {if no_results}{redirect="404"}{/if}
    <!--Code that shows individual article-->
  {/exp:channel:entries}
{/if}

The problem is even when you go to /widgets the redirect fires. If I recall correctly this is because even though the conditional if segment 2 is not empty is untrue the parser still goes the channel entries tag anyway and as soon as it hits the redirect it fire.

So the question is how would you implement a 404 for this example.

  • Is this a case wherein you are using the same template to display the list view as well as a single entry view? – Jean St-Amand Apr 5 '13 at 1:46
  • Yes same template for both – Phil Apr 5 '13 at 2:04
1

I'd look to use switchee rather then {if}

{exp:switchee variable="{segment_2}"}
  {case value=""}{!-- Nothing is segment_2 --}
    {exp:channel:entries channel="{segment_1}" limit="8"}
      <!--Code showing article list-->
    {/exp:channel:entries}
  {/case}

  {case default="yes"}{!-- Assume there is something in segment_2 --}
    {exp:channel:entries channel="{segment_1}" limit="1" require_entry="yes"}
      {if switchee_no_results}{redirect="404"}{/if}  
      <!--Code that shows individual article-->
    {/exp:channel:entries}
  {/case}
{/exp:switchee}

This is all untested and not to be interpreted as a literal answer – more a guide ;)

| improve this answer | |
  • I hadn't seen switchee before. Its amazing I should be able to get some performance boost here and there too. Normally I build with structure and you get in a groove with a certain way of doing things. This site doesn't want to use it so I am relearning a few things. Thanks for the help. – Phil Apr 5 '13 at 5:34

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.