maz*_*iak 11 php zend-framework zend-framework-mvc
使用Zend Framework中设置的标准MVC,我希望能够显示具有锚点的页面.现在我只是在.phtml文件中添加一个我想要的'#anchor'的无意义参数.
<?= $this->url(array(
'controller'=>'my.controller',
'action'=>'my.action',
'anchor'=>'#myanchor'
));
Run Code Online (Sandbox Code Playgroud)
这将URL设置为/my.controller/my.action/anchor/#myanchor
有没有更好的方法来实现这一目标?导航到锚链接后,额外的项参数将在用户的URL中设置,这是我不想发生的事情.
Mar*_*zus 13
其中一种可能性是覆盖url helper或创建一个新的hell.
class My_View_Helper_Url extends Zend_View_Helper_Url
{
public function url(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
{
if (isset($urlOptions['anchor']) && !empty($urlOptions['anchor']))
{
$anchor = $urlOptions['anchor'];
unset($urlOptions['anchor']);
}
else
{
$anchor = '';
}
return parent::url($urlOptions, $name, $reset, $encode).$anchor;
}
}
Run Code Online (Sandbox Code Playgroud)
这个帮助器覆盖url helper,问题是,你不能使用名为'anchor'的参数,因为它会在url中改成锚点.
你会在你的例子中称之为
<?= $this->url(array(
'controller'=>'my.controller',
'action'=>'my.action',
'anchor'=>'#myanchor'
));
Run Code Online (Sandbox Code Playgroud)
我希望它有所帮助
有多种方法可以将片段ID实现到您的URL中.以下是一些选项,以及每个选项的优缺点.
您可以"#$fragment_id"在url()通话后添加.不雅,但很简单.如果您不使用页面锚点(即仅一页或两页),这是要走的路.
url()助手您可以编写一个自定义版本,url()为片段ID附加可选的第5个参数:
class My_View_Helper_Url extends Zend_View_Helper_Url
{
public function url(array $urlOptions = array(), $name = null,
$reset = false, $encode = true,
$fragment_id = null)
{
$uri = parent::url($urlOptions, $name, $reset, $encode);
if(!is_null($fragment_id)) {
$uri .= "#$fragment_id";
}
return $uri;
}
}
Run Code Online (Sandbox Code Playgroud)
这样,锚(和锚/片段id)信息严格地保持视图的领域.这对于一般用途很有用,但对于默认路由可能会有点笨拙.此外,对于某些用途,这仍然有点太硬编码.
Route类(Extreme)作为第三个选项,您可以编写类的自定义版本Zend_Controller_Router_Route,特别是assemble($data, $reset, $encode)方法(match($path)默认情况下该方法忽略片段ID).
使用这种方法可能非常棘手,但非常有用,特别是如果使用仅限于特定路由(此方法可用于将片段id基于任何变量).
使用片段ID时必须考虑某些注意事项.例如,查询字符串必须位于uri中的片段id之前,否则,PHP将忽略查询字符串.但是,大多数ZF应用程序倾向于避免使用查询字符串,因此它可能不是问题.
小智 5
url视图助手接受第三个选项的"片段"键:
url('[route]',array([params]),array('fragment'=>'anchor'));
Run Code Online (Sandbox Code Playgroud)
这将自动结束#anchor的网址.
- 感谢Exlord