【问题标题】:Get Current URL in Magento and show something在 Magento 中获取当前 URL 并显示一些东西
【发布时间】:2014-10-01 06:24:49
【问题描述】:

我正在尝试在 Magento 中获取当前 URL,如果我当前在该页面上,则显示一些内容。到目前为止,这就是我所做的并且成功了。

 <?php
 $currentUrl = $this->helper('core/url')->getCurrentUrl();
 ?>     

 <?php if($currentUrl === 'http://powerplantv2.jehzlau.net/blog') { ?>I am in the blog page<?php } ?>

但是我不想硬编码源代码中的URL,因为如果我转移到另一个服务器,我需要再次修改phtml文件。

我尝试了我在网上找到的所有方法,但没有奏效。我希望这里的一些 Magento 专家可以启发我我做错了什么。 :(

【问题讨论】:

  • 无论如何,我能够使用 substr 解决我自己的问题。我注意到 blogUrl 最后有一个 /,所以我使用 substr 删除了它,因此这段代码现在可以立即在特定页面上显示某些内容。 :D code helper('core/url')->getCurrentUrl(); $blogUrl = $this->getUrl('blog'); $blogfixedurl = substr($blogUrl, 0, -1); ?> 您目前在博客页面code 不过如果有人有更好的解决方案,欢迎回答。我认为我的代码可以缩短。 :D

标签: php magento


【解决方案1】:

您可以通过执行以下操作来检索当前 URL 路径:

$currentUrl = Mage::helper('core/url')->getCurrentUrl();
$url = Mage::getSingleton('core/url')->parseUrl($currentUrl);
$path = $url->getPath();

然后使用一些基本逻辑,您可以定位/blog 页面。

$blogPaths = array('/blog', '/blog/', '/index.php/blog/');
if(in_array($path, $blogPaths))
{
    //Do something on /blog
}

【讨论】:

  • 哦,好人..谢谢你。从来没有想过使用数组。我只是把它修整了,但会使用这个技巧,这样即使 url 重写关闭,它仍然可以工作。谢谢阿克塞尔。 :D
【解决方案2】:

另一种解决方案是检查被调用的控制器。检查这些的输出,看看它是否适合你。这适用于模板文件。

 /**
 * get Controller name
 */
$this->getRequest()->getControllerName();

/**
 * get Action name, i.e. the function inside the controller
 */
$this->getRequest()->getActionName();

/**
 * get Router name
 */
$this->getRequest()->getRouteName();

/**
 * get module name
 */
$this->getRequest()->getModuleName();

【讨论】:

    【解决方案3】:
    $currentUrl = Mage::helper('core/url')->getCurrentUrl();
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性 cmets 挤满你的代码,因为这会降低代码和解释的可读性!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2015-03-06
    • 2011-12-09
    相关资源
    最近更新 更多