In RazorCompiler, support expressions with non-string or null values

This commit is contained in:
Steve Sanderson 2018-01-16 16:30:29 +00:00
parent 8c2a32b87c
commit 5949045319
5 changed files with 50 additions and 2 deletions

View File

@ -59,6 +59,13 @@ namespace Microsoft.Blazor.RenderTree
public void AddText(string textContent)
=> Append(RenderTreeNode.Text(textContent));
/// <summary>
/// Appends a node representing text content.
/// </summary>
/// <param name="textContent">Content for the new text node.</param>
public void AddText(object textContent)
=> AddText(textContent?.ToString());
/// <summary>
/// Appends a node representing a string-valued attribute.
/// The attribute is associated with the most recently added element.

View File

@ -77,7 +77,7 @@ namespace Microsoft.Blazor.RenderTree
internal static RenderTreeNode Text(string textContent) => new RenderTreeNode
{
NodeType = RenderTreeNodeType.Text,
TextContent = textContent,
TextContent = textContent ?? string.Empty,
};
internal static RenderTreeNode Attribute(string name, string value) => new RenderTreeNode

View File

@ -100,6 +100,25 @@ namespace Microsoft.Blazor.Build.Test
node => AssertNode.Text(node, "Some plain text"));
}
[Fact]
public void SupportsCSharpExpressions()
{
// Arrange/Act
var component = CompileToComponent(@"
@(""Hello"")
@((object)null)
@(123)
@(new object())
");
// Assert
var nodes = GetRenderTree(component).Where(NotWhitespace);
Assert.Collection(nodes,
node => AssertNode.Text(node, "Hello"),
node => AssertNode.Text(node, "123"),
node => AssertNode.Text(node, new object().ToString()));
}
[Fact]
public void SupportsCSharpFunctionsBlock()
{

View File

@ -40,9 +40,11 @@ namespace Microsoft.Blazor.Test
{
// Arrange
var builder = new RenderTreeBuilder(new TestRenderer());
var nullString = (string)null;
// Act
builder.AddText("First item");
builder.AddText(nullString);
builder.AddText("Second item");
// Assert
@ -50,9 +52,29 @@ namespace Microsoft.Blazor.Test
Assert.Equal(0, nodes.Offset);
Assert.Collection(nodes,
node => AssertNode.Text(node, "First item"),
node => AssertNode.Text(node, string.Empty),
node => AssertNode.Text(node, "Second item"));
}
[Fact]
public void CanAddNonStringValueAsText()
{
// Arrange
var builder = new RenderTreeBuilder(new TestRenderer());
var nullObject = (object)null;
// Act
builder.AddText(1234);
builder.AddText(nullObject);
// Assert
var nodes = builder.GetNodes();
Assert.Equal(0, nodes.Offset);
Assert.Collection(nodes,
node => AssertNode.Text(node, "1234"),
node => AssertNode.Text(node, string.Empty));
}
[Fact]
public void UnclosedElementsHaveNoEndDescendantIndex()
{

View File

@ -1,5 +1,5 @@
<h1>Counter</h1>
<p>Current count: @currentCount.ToString()</p>
<p>Current count: @currentCount</p>
<button onclick=@OnButtonClicked>Click me</button>
@functions {