4

我正在 Laravel 中建立一个博客,但似乎无法弄清楚如何使用HTML::link(..). 例如,我在博客中有指向不同类别的链接,例如部门新闻,我正在尝试获取格式如下的链接 - http://localhost/blog/category/department+news.,其中Department News$post->category

我试过下面的代码,它产生http://localhost/blog/Department News

{{ HTML::link('admin/blog/category/' . $post->category, $post->category) }}

我怎样才能逃避这个并生成所需的 URL?

4

2 回答 2

7

Usually, you'd have each post category use a slug column in the database for the URL fragment, and then use something like:

HTML::link('blog/category/'.$post->category->slug, $post->category->name)

There's appears to be no way with Laravel to automatically encode only certain parts of the URL, so you'd have to do it yourself:

HTML::link(
    'admin/blog/category/'.urlencode(strtolower($post->category)),
    $post->category
)

You might want to consider using the "slug" approach. You don't necessarily have to store it in the database, you could have your class generate it on the fly:

class Category {
    function slug() {
        return urlencode(strtolower($this->name));
    }
}

I'm not sure what you're working with exactly, but hopefully you get the idea.

于 2013-01-07T17:09:24.787 回答
0

对不起。我不同意韦斯利,这行得通...

如果您使用命名路由,则Url::route('category_browse',[category])调用将对值进行编码。route 方法中的第二个参数允许混合内容。因此,如果您的路线中只有一个参数,您可以传递一个值,否则是一个数组。

在树枝(TwigBridge)中,这是...

{{ url_route('category_browse',[category]) }} 

否则(刀片)它应该是......

{{ Url::route('category_browse',[category]) }}

你的名字路线应该是这样的......

Route::any('/blog/category/{category}',
    array(
        /*'before'=>'auth_check', -- maybe add a pre-filter */
        'uses' =>'BlogController@category',
        'as' => 'category_browse'
    )
);
于 2014-05-02T11:29:34.643 回答