Skip to content

Instantly share code, notes, and snippets.

@schotime
Last active October 8, 2015 11:18
Show Gist options
  • Save schotime/3324006 to your computer and use it in GitHub Desktop.
Save schotime/3324006 to your computer and use it in GitHub Desktop.
Spark Optional Attributes
public static class BindingExtensions
{
public static HtmlTag Data(this HtmlTag html, Dictionary<string, object> dataattrs)
{
foreach (var item in dataattrs)
{
html.Data(item.Key, item.Value);
}
return html;
}
public static HtmlTag Attr(this HtmlTag html, Dictionary<string, object> attrs)
{
foreach (var item in attrs)
{
html.Attr(item.Key, item.Value);
}
return html;
}
public static HtmlTag SetStyle(this HtmlTag html, string styles)
{
if (string.IsNullOrEmpty((styles ?? "").Trim()))
return html;
var stylesArr = styles.Split(';');
foreach (var style in stylesArr)
{
var parts = style.Split(':');
if (parts.Length < 2)
continue;
html.Style(parts[0], parts[1]);
}
return html;
}
}
<?xml version="1.0" encoding="utf-8" ?>
<bindings>
<element name="input">
Html.Input(x=>x.@For)
.Data(new Dictionary[[string,object]]{{"@data-*"}})
.Attr(new Dictionary[[string,object]]{{"@*"}})
.SetStyle("@@style")
.AddClass("@@class")
</element>
</bindings>
<?xml version="1.0" encoding="utf-8" ?>
<bindings>
<element name="todo">
Html.Todo("@item", "@@extra")
</element>
</bindings>
public static class Extension {
public static HtmlString Todo(this HtmlHelper html, string item, string extra) {
string str = string.Format("<li>{0}{1}</li>",
html.Encode(item), (string.IsNullOrEmpty(msg) ? "" : " - " + html.Encode(extra)));
return MvcHtmlString.Create(str);
}
}
<todo item="this is the item"/> renders <li>this is the item</li>
<todo item="this is the item" extra="do it soon"/> renders <li>this is the item - do it soon</li>
//These attributes will add to the ones that have already been applied by HTML conventions
<input For="Name" class="todo" style="border:1px solid blue;color:green" data-time="23423425522" />
// Is equivalent to
${Html.Input(x=>x.Name)
.AddClass("todo")
.Style("border","1px solid blue")
.Style("color","green")
.Data("time","23423425522")}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment