shuhelohelo’s blog

Xamarin.Forms多めです.

Blazorで文字列をHTMLとしてページ内に出力する

Blazorで変数に格納された文字列としてのHTMLは、そのまま変数をページ内に出力すると適切にエスケープされてそのまま文字列として表示されます。

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />


<div>
    @MyHtml
</div>

@functions{
    string MyHtml { get; set; } = "<h1>hello</h1>";
}

f:id:shuhelohelo:20190531162052p:plain

これを文字列としてではなく、タグが評価された結果として表示したいことがあります。

そういうときは、文字列をMarkupString型にキャストするとよいです。

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />


<div>
    @((MarkupString)MyHtml)
</div>

@functions{
    string MyHtml { get; set; } = "<h1>hello</h1>";
}

すると、文字列がHTMLとして出力されます。

f:id:shuhelohelo:20190531162321p:plain