编辑我使用 Symfony 3.2
好的,我自己找到了解决方案。这就是我所做的。
首先从 symfony 文档中阅读此内容。使用 ConvertParamater 真的很容易实现http://symfony.com/doc/current/best_practices/controllers.html#using-the-paramconverter
实施后:
安装 StofDoctrineExtensionBundle
在 composer.json 中
“要求”:{
“stof/doctrine-extensions-bundle”:“~1.1”
}
别忘了更新 appKernel.php 文件
<?php
// app/AppKernel.php
public function registerBundles()
{
return array(
// …
new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
// …
);
}
然后我配置config.yml文件:
# app/config/config.yml
# Stof\DoctrineExtensionsBundle configuration
stof_doctrine_extensions:
orm:
default:
sluggable: true
然后我向我的新闻实体添加一个 slug 属性:
private $slug;
然后我更新我的 News.orm.yml 文件
蛞蝓:
类型:字符串
长度:255
唯一:假
格莫:
蛞蝓:
分隔器: _
款式:骆驼
领域:
- 标题
那我做
doctrine:generate:entites myBundle:News
还有`doctrine:schema:update --force
这在我的 News 表中创建了一个 slug 字段。因为这个字段可能不为空,所以我手动输入了一些值,所以我的 News 表的每一行都有一个有效的 slug
然后在我的 NewsController 中使用这行代码:
$this->generateUrl('myroute_news_show_one_by_id', array('slug' => $news->getSlug()), UrlGeneratorInterface::ABSOLUTE_URL);
return $this->render('MyBundle:News:single_post.html.twig', [
'news' => $news,
'tags' => $arrTagNames
]);`
在我的 Twig 模板中,我创建了显示一条新闻的链接:
<a href="{{ path('myroute_show_one_by_id', {'slug': news.slug}) }}">{{news.title}}</a>
我希望这可以帮助其他人