Skip to content

Partials

Itay edited this page Aug 26, 2018 · 1 revision

You can create partials for elements you use alot:

public static EmptyTag EnterPasswordInput(string placeholder)
{
    return PasswordInput("enterPassword", placeholder);
}

public static EmptyTag ChoosePasswordInput(string placeholder)
{
    return PasswordInput("choosePassword", placeholder);
}

public static EmptyTag RepeatPasswordInput(string placeholder)
{
    return PasswordInput("repeatPassword", placeholder);
}

public static EmptyTag PasswordInput(string identifier, string placeholder)
{
    return Input()
                .WithType("password")
                .WithId(identifier)
                .WithName(identifier)
                .WithPlaceholder(placeholder)
                .IsRequired();
}

public static EmptyTag EmailInput(string placeholder)
{
    return Input()
                .WithType("email")
                .WithId("email")
                .WithName("email")
                .WithPlaceholder(placeholder)
                .IsRequired();
}

public static ContainerTag SubmitButton(string text)
{
    return Button(text).WithType("submit");
}

The equivalent HTML would be:

<input
    type="password"
    id="enterPassword"
    name="enterPassword"
    placeholder="Enter password"
    required
    >

<input
    type="password"
    id="choosePassword"
    name="choosePassword"
    placeholder="Choose password"
    required
    >

<input
    type="password"
    id="repeatPassword"
    name="repeatPassword"
    placeholder="Repeat password"
    required
    >

<input
    type="email"
    id="email"
    name="email"
    placeholder="Email"
    required
    >

<button type="submit">Text</button>

You can use these partials, for example in the registration form:

H1("Please sign up"),
Form().WithMethod("post").With(
    EmailInput("Email Address"),
    ChoosePasswordInput("Choose Password"),
    RepeatPasswordInput("Repeat Password"),
    SubmitButton("Sign up")
)

Pretty clean, right? The rendered HTML is more verbose:

<h1>Please sign up</h1>
<form method="post">
    <input type="email" id="email" name="email" placeholder="Email address" required>
    <input type="password" id="choosePassword" name="choosePassword" placeholder="Choose password" required>
    <input type="password" id="repeatPassword" name="repeatPassword" placeholder="Repeat password" required>
    <button type="submit">Sign up</button>
</form>

Imagine if you wanted labels in addition. The C# snippet would look almost identical: You could create a partial called PasswordAndLabel() and nothing but the method name would change. The resulting HTML however, would be twice or thrice as big, depending on whether or not you wrapped the input and label in another tag.