如何在 Blazor 组件 HTML 属性中转义 @?

How do I Escape @ in Blazor Component HTML Attributes?

我想使用 <InputText /> 渲染以下内容:

<input placeholder="@Handle" class="valid">

这是我尝试过的:

<InputText @bind-Value="Handle" placeholder="Handle" />    @* <- Compiles, but not what I want. *@
<InputText @bind-Value="Handle" placeholder="@@Handle" />  @* <- Fails. *@

但是我得到以下错误:

RAZORGENERATE : error RZ9986: Component attributes do not support complex content (mixed C# and markup). 
Attribute: 'placeholder', text: '"@"Handle'

所以使用 @@ 在技术上仍然是剃须刀代码(转义的“@”)并且不能与属性一起使用。我怎样才能在 HTML 属性中放置一个“@”?

我正在使用 .NET 5.0,服务器端 Blazor。

HTML 解决方案

立即意识到我可以只使用 HTML 字符代码。这有效:

<InputText @bind-Value="@Inputs.Handle" placeholder="&#64;Handle" />

剃须刀解决方案

或者,我可以只使用剃须刀来执行此操作:

<InputText @bind-Value="@Inputs.Handle" placeholder="@("@UserHandle")" />

道德是,你不能在组件属性中将 razor 与原始 HTML 组合(并且知道 @@ 仍然是 razor 语法)。选择 一个 就可以了。

我只是想补充另一种可能性 您可以添加类似

的内容
@code{
    private const string placeholder = "@Handle";
}

然后

<InputText @bind-Value="@Inputs.Handle" placeholder="@placeholder" />

但这很快就会变得非常大,并且无法回答“如何在剃须刀组件中转义 @”这个问题。也许问微软?