2016-04-26 3 views
4

は、私は、単一のコンポーネントに抽象化したいコンテンツのこれらの繰り返しのブロックを持っている:この繰り返しパターンをASP.NET MVC 5で抽象化するにはどうすればよいですか?私のテンプレートで

<header class="Component-header"> 
    <!-- Some content here is always the same --> 
    <!-- And some content is different for each use --> 
</header> 
<div class="Component-body"> 
    <!-- Some content here is always the same --> 
    <!-- And some content is different for each use --> 
</div> 
<footer class="Component-footer"> 
    <!-- Some content here is always the same --> 
    <!-- And some content is different for each use --> 
</footer> 

通常、私は、このためにかみそり部分図を使用し、それをいくつかの変数を渡します。しかし、この場合は、htmlの大きな塊を変数として渡すことになりますが、これは賢明に見えません。

私はこの記事を見つけました:http://www.growingwiththeweb.com/2012/09/custom-helper-for-surrounding-block-in.html、ブロックヘルパーの作成方法について説明しています。私がやろうとしていることにもう少し近いですが、htmlを文字列として定義する必要があります。これは、必要なものではありません(htmlの量は維持できなくなるほどで​​す)。

私が理解していることから、コンポーネントは1ページに複数回出現するため、このためにレイアウトを使用することはできません。ですから私の質問は、上記のパターンを再利用可能な単一のコンポーネントに抽象化するにはどうすればいいですか?複数のHTML領域を受け入れ、変数を受け入れるページで再利用できますか?

+0

機能的には私が欲しいものemberjsは、コンポーネントを処理する方法に似ています。https://guides.emberjs .com/v1.10.0/components/wrapping-content-in-a-component /ですが、私が望むのは複数の「yield」領域を持つということです。 – vsjn3290ckjnaoij2jikndckjb

+0

この問題を抽象化したフロントエンドのフレームワークをルックアップすることもできるので、適切なビューロジックを扱うだけで済みます。 Aurelia、ReactJs、AngularJSなどのフレームワーク1/2 –

+0

@CallumLiningtonあなたは.net mvcと組み合わせて使用​​することを意味しますか? – vsjn3290ckjnaoij2jikndckjb

答えて

1

私のために働くものは、かみそりを使用しています@helper。以下のコードはApp_Codeにあり、ここでファイルYourComponentName.cshtmlを作成します。そのファイルに次のマークアップを使用します。

@using System.Web.Mvc; 

@helper Render(
    ViewContext context, 
    string title = "Default title", 
    Func<object, object> header = null, 
    Func<object, object> content = null, 
    Func<object, object> footer = null 
) 
{ 
    <header class="Component-header"> 
    <!-- Some content here is always the same --> 
    <h3>@title</h3> 
    @if (header != null) { @header.DynamicInvoke(context); } 
    </header> 
    <div class="Component-content"> 
    <!-- Some content here is always the same --> 
    @if (content != null) { @content.DynamicInvoke(context); } 
    </div> 
    <footer class="Component-footer"> 
    <!-- Some content here is always the same --> 
    @if (footer != null) { @footer.DynamicInvoke(context); } 
    </footer> 
} 

その後、あなたとあなたのテンプレートでコンポーネントを使用することができます。

@YourComponentName.Render(
    ViewContext, 
    title: "Title", 
    header: @<p>Markup for the header</p>, 
    content: @<p>The content</p>, 
    footer: @<p>Markup for the footer</p> 
) 
関連する問題