Single line razor

I want to write a Razor view helper to create the contents of a single line:

@helper Format(obj) { <text> @obj.Title @obj.FormatInnerData() (obj.User != null) { @obj.User.Name } <text> } 

But of course I get

 Title Inner Data User Name 

I have to do now

 <text>@obj.Title @obj.FormatInnerData() @(obj.User != null ? obj.User.Name : "")</text> 

to output text as a separate line without line breaks, but for many properties this can grow quite a long / unreadable.

In other words, how is it more convenient for me to use Razor to generate text content, and not to mark up the content?

UPD: Ideally, it would be something like

  <content>@obj.Title</content> <content>@obj.Format() @obj.User.Name</content> 

i.e. only parts between content tags are included in the output stream. Of course, perhaps a simpler syntax like @: instead of <text>.

An example of use is the generation of the contents of a JavaScript string with markup inside or the creation of text files with license data in the format "Key: name (details)" in each line, filled with spaces for grouping.

+4
source share
4 answers

So, if I understand you correctly, would you like to specify your views with several lines, while in the end the output would be on one line?

I don't think this is possible out of the box, but you can write your own custom RazorViewEngine (derived from a real RazorViewEngine) that cuts out all new lines before returning the view.

+1
source

You can create a helper method like this

 public class MyHelper { public static string JoinedString(string delimiter, params object[] parameters) { return string.Join(delimiter, parameters); } } 

And then call it in Razor mode like

 MyHelper.JoinedString("", "<text>", @obj.Title, obj.User == null ? "" : obj.User.Name "</text>") 

Note that the implementation is generic and you can use any separator (in this case, an empty string).

+1
source

You tried

 @helper Format(obj) { <text> @( obj.Title + obj.FormatInnerData() + obj.User != null ? obj.User.Name : "" ) <text> } 
0
source

Here's a partially useful solution:

 @helper Format(obj) { <text>@(obj.Title ) @(obj.FormatInnerData() ) @(obj.User != null ? obj.User.Name : "")<text> } 

those. we transfer the code to the next line, not to the content, so the new lines inside @ () are not written to the output.

0
source

All Articles