#2 Template-Delegate Helpers - Razor-Style Functions
Reuse Code Snippet with Func<dynamic,object>
Template Delegate
If you just need a quick simple snippet, Template Delegates are the way to go.
They are very limited so only ideal for simple stuff. More complex stuff should use
Razor Components with @Html.Partial and DynamicModel.
Note that in the following code item
is the thing passed into the function.
-
this is text, it doesn't have tags
-
this string has html tags
-
this is just a bold line
Complex Data with Func<dynamic,object>
Template Delegate
if you have multiple values, you need to merge in into one object like this:
@{
// Simple Hybrid (Dnn/Oqtane) Template Delegate
Func<dynamic, dynamic> FancyLink = @<li>
<strong style="color: @item.Color">
@Html.Raw(item.Label)
@if(item.AddStar) {
<text>🌟</text>
}
</strong>
</li>;
}
-
this is text, it doesn't have tags
🌟
-
this string has html tags
#2 Template-Delegate Helpers - Razor-Style Functions
@inherits Custom.Hybrid.Razor14
<!-- unimportant stuff, hidden -->
@{
var normalText = "this is text, it doesn't have tags";
var htmlText = "this string <em>has</em> html <strong>tags</strong>";
}
<div class="row">
<div class="col-lg-7">
<h2>Reuse Code Snippet with <code>Func<dynamic,object></code> Template Delegate</h2>
<p>If you just need a quick simple snippet, Template Delegates are the way to go.
They are very limited so only ideal for simple stuff. More complex stuff should use
@linker.TutLink("Razor Components with @Html.Partial and DynamicModel", "reuse110").
</p>
<div>
Note that in the following code <code>item</code> is the thing passed into the function.
</div>
@{
// Simple Hybrid (Dnn/Oqtane) Template Delegate
Func<dynamic, object> BoldLi = @<li>
<strong>
@Html.Raw(item)
</strong>
</li>;
}
<ul>
@BoldLi(normalText)
@BoldLi(htmlText)
@BoldLi("this is just a bold line")
</ul>
</div>
@Html.Partial("../shared/_DefaultInfoSection.cshtml")
</div>
<trim>
<hr>
<h2>Complex Data with <code>Func<dynamic,object></code> Template Delegate</h2>
<p>if you have multiple values, you need to merge in into one object like this: </p>
@{
// Simple Hybrid (Dnn/Oqtane) Template Delegate
Func<dynamic, dynamic> FancyLink = @<li>
<strong style="color: @item.Color">
@Html.Raw(item.Label)
@if(item.AddStar) {
<text>🌟</text>
}
</strong>
</li>;
}
<ul>
@FancyLink(new { Label = normalText, Color = "red", AddStar = true })
@FancyLink(new { Label = htmlText, Color = "lime", AddStar = false })
</ul>
<!-- unimportant stuff, hidden -->