Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't one Razor helper call another helper?

I'm running the razor code below in a .cshtml file (it's a simplified version of something more complex that I need to achieve), but the renderTestB helper does not seem to execute.

@renderTestA("test string 1", "test string 2");

@helper renderTestA(string input1, string input2)
{
    <div>
        @renderTestB(input1)
        @renderTestB(input2)
    </div>
}

@helper renderTestB(string input)
{
    <p class="test">@input</p>
}

Why is this? And is there another way of achieving what I'm trying to do?

I realise I could duplicate the paragraph code within the renderTestA helper, but would obviously prefer a re-usable code solution.

like image 835
lozz Avatar asked Jul 08 '15 12:07

lozz


1 Answers

What about something like this?

@renderTestA(renderTestB("test string 1"), renderTestB("test string 2"))

@helper renderTestA(string input1, string input2)
{
    <div>
        @input1
        @input2
    </div>
}

@helper renderTestB(string input)
{
    <p class="test">@input</p>
}

You should consider using Editor / Display templates or custom HTML helpers instead as the @helper functionality was used back before these features became the norm.

As to why you cannot nest them. It introduces a number of problems that are easily avoided by using the syntax I suggested above. Such as... if you have a circular loop of nested helpers, it could easily cause a stack overflow.

like image 184
Brad C Avatar answered Oct 22 '22 20:10

Brad C