LoginSignup
1
1

More than 5 years have passed since last update.

Nancy.Linkerパッケージを試してみた

Posted at

ここで紹介されていた Nancy.Linker パッケージを試してみました。ビューにはRazorを使っています。

これは何?

リンク先としてルート名を渡すと、それに見合った相対パスや絶対パスを出力してくれるクラスを含むパッケージ。

使い方

パッケージのインストール

Nugetでインストールするだけ

install-package Nancy.Linker

モジュールクラス作成

コンストラクタでIResourceLinker型値を受け取るようにします。

あとは、ビューモデルにIResourceLinker型とNancyContext型のプロパティを持たせる必要があります。

これについては、重複がひどいことになるのが気持ち悪い。。(そもそもビューモデルに渡す内容か?)

using Nancy.Linker;
...

public class MainModule : NancyModule
{
    public MainModule(IResourceLinker linker) : base() 
    {
        //ルート名, パス
        Get["root", "/"] = _ =>
            Negotiate
                .WithModel(new { Linker = linker, Context = this.Context })
                .WithView("index");

        Get["top", "/top"] = _ =>
            Negotiate
                .WithModel(new { Linker = linker, Context = this.Context })
                .WithView("index");

        Get["bar", "/bar"] = _ =>
            Negotiate
                .WithModel(new { Linker = linker, Context = this.Context })
                .WithView("bar");

        Get["hogetop", "/hoge/top"] = _ =>
            Negotiate
                .WithModel(new{Linker = linker, Context = this.Context})
                .WithView("hoge");
    }
}

ビュー(index.cshtml)

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    <ul>
        <!-- BuildRelativeUri()の第二引数がルート名 -->
        <li><a href=@Model.Linker.BuildRelativeUri(Model.Context, "hogetop")>Hoge Link</a></li>
        <li><a href=@Model.Linker.BuildRelativeUri(Model.Context, "bar")>Bar Link</a></li>
    </ul>
</body>
</html>

ビュー(hoge.cshtml)

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ほげ</title>
</head>
<body>
    <div>
        <p>Hoge!!!</p>
        <!-- BuildRelativeUri()の第二引数がルート名 -->
        <a href=@Model.Linker.BuildRelativeUri(Model.Context, "top")>Goto Top</a>
    </div>
</body>
</html>

ビュー(bar.cshtml)

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>BarPage</title>
</head>
<body>
    <div>
        <p>Bar!!!</p>
        <!-- BuildRelativeUri()の第二引数がルート名 -->
        <a href=@Model.Linker.BuildRelativeUri(Model.Context, "top")>Goto Top</a>
    </div>
</body>
</html>
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1