获取Magento中的当前URL并显示一些内容

jeh*_*lau 28 php magento

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

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

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

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

我尝试了我在网上找到的所有内容,但它没有用.我希望这里的一些Magento专家能够让我知道我做错了什么.:(

Axe*_*xel 73

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

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

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

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


esp*_*ley 5

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

 /**
 * 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();
Run Code Online (Sandbox Code Playgroud)


Pan*_*yay 5

$currentUrl = Mage::helper('core/url')->getCurrentUrl();
Run Code Online (Sandbox Code Playgroud)

  • 尽管此代码段可以解决问题,但是[包括说明](// meta.stackexchange.com/questions/114762/explaining-entrely-code-based-answers)确实有助于提高您的帖子质量。请记住,您将来会为读者回答这个问题,而这些人可能不知道您提出代码建议的原因。也请尽量不要在代码中添加解释性注释,因为这会降低代码和解释的可读性! (2认同)