[英]CodeIgniter PHP: how to echo a URL segment only if that segment actually exists
OK, I've been trying to figure this one out for 3 days, but I can't seem to get it right.好的,我已经尝试解决这个问题 3 天了,但我似乎无法正确解决。 I'm trying to conditionally echo a URL segment (the page number) only if that segment actually exists for the particular webpage.
仅当特定网页确实存在该段时,我才尝试有条件地回显 URL 段(页码)。 Specifically, I'm dealing with the canonical tag in my header template.
具体来说,我正在处理标题模板中的规范标签。
THE BACKGROUND:背景:
My current code echos paginated directory pages as desired, like this:我当前的代码根据需要回显分页目录页面,如下所示:
https://www.example.com/subjects/apples/2
https://www.example.com/subjects/apples/3
https://www.example.com/subjects/apples/4
etc.
It echos directory home pages as NOT desired, like this:它按照不需要的方式回显目录主页,如下所示:
https://www.example.com/subjects/apples/
WHAT MUST STAY THE SAME:必须保持不变:
Paginated directory URLs do NOT end with a forward slash, which is good.分页目录 URL 不以正斜杠结尾,这很好。
WHAT MUST CHANGE:必须改变的地方:
Directory home pages DO end with a forward slash, which is bad.目录主页确实以正斜杠结尾,这是不好的。
THE EXISTING CODE:现有代码:
<link rel="canonical" href="<?php echo $this->config->item("base_url");?><?php echo $category_in_url;?>/<?php echo $this->uri->segment(2);?>" />
THE DESIRED OUTCOME:预期的结果:
Directory home pages must NOT end with a forward slash.目录主页不得以正斜杠结尾。 To stop leaving behind an orphaned forward slash at the end of directory home page URLs, your new code will echo
要停止在目录主页 URL 末尾留下孤立的正斜杠,您的新代码将回显
/<?php echo $this->uri->segment(2);?>
only if segment 2 (ie, a page number of 2+) actually exists for the particular webpage.仅当特定网页实际存在第 2 段(即,页码为 2+)时。 Pages 0 and 1 do not receive a page number in the URL.
第 0 页和第 1 页在 URL 中没有页码。 So, starting with Page 2, I need to echo that part.
所以,从第 2 页开始,我需要回应那部分。 Paginated directory pages should look like this:
分页目录页面应如下所示:
https://www.example.com/subjects/apples/4
Directory home pages should look like this:目录主页应如下所示:
https://www.example.com/subjects/apples
NOTE: Your solution has to work with my existing code without breaking the PHP.注意:您的解决方案必须在不破坏 PHP 的情况下使用我现有的代码。
Thank you in advance for your much-appreciated help!在此先感谢您的大力帮助!
Jason杰森
<link rel="canonical" href="<?php echo $this->config->item("base_url");?><?php echo $category_in_url.((int)$this->uri->segment(2,0) > 1 ? '/'.$this->uri->segment(2) : '');?>" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.