5

I'm using HtmlTextWriter to output html to a stream. However, I'm missing a way to write html comments. Of course, I could write an extension method doing

public static void WriteComment(this HtmlTextWriter writer, string comment)
{
  writer.Write("<!-- ");
  writer.WriteEncodedText(comment);
  writer.Write(" -->");
}

But that does feel a bit inelegant - is there some built-in method I'm not seeing?

skolima
  • 31,963
  • 27
  • 115
  • 151
  • 2
    Not quite the answer you're looking for, but a little more elegant: `writer.Write("");` – Nolonar Feb 07 '13 at 10:30
  • Its just another tag, no? We don't have a seperate method for each valid tag name in an\the HTML specification. – Jodrell Feb 07 '13 at 10:34
  • 1
    I like your extension. It's spot on and elegant. – Richard Schneider Feb 07 '13 at 10:36
  • @Jodrell: comment is not a tag, that's the whole problem. – skolima Feb 07 '13 at 10:45
  • @Nolonar: good catch, but since comment's contents still have to be valid HTML (see http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.4 ) I prefer the `WriteEncodedText` for them, safer solution. – skolima Feb 07 '13 at 10:53
  • I don't think that the specification says the comments have to be valid HTML. What if I wanted to write `<`, `>` or `&` into my comment? I don't doubt that, in practice, your method would work fine but, If I were extending the framework for everybody ... – Jodrell Feb 07 '13 at 11:05

1 Answers1

2

I can argue, after checking the specification, that these extensions could be marginally more correct,

public static void WriteBeginComment(this HtmlTextWriter writer)
{
    writer.Write(HtmlTextWriter.TagLeftChar);
    writer.Write("!--");
}

public static void WriteEndComment(this HtmlTextWriter writer)
{
    writer.Write("--");
    writer.Write(HtmlTextWriter.TagRightChar);
}

public static void WriteComment(this HtmlTextWriter writer, string comment)
{
    if (
        comment.StartsWith(">") || 
        comment.StartsWith("->") || 
        comment.Contains("--") ||
        comment.EndsWith("-"))
    {
        throw new ArgumentException(
            "text does not meet HTML5 specification",
            "comment");
    }

    writer.WriteBeginComment();
    writer.Write(comment);
    writer.WriteEndComment();
}
skolima
  • 31,963
  • 27
  • 115
  • 151
Jodrell
  • 34,946
  • 5
  • 87
  • 124
  • After reading [HTML comments within comments](http://stackoverflow.com/q/3773719/3205) I was sure that `WriteEncodedText` is needed, but after testing this with w3c validator and in browser, seems that your safeguards are sufficient. Accepted. – skolima Feb 07 '13 at 12:05
  • @skolima, there appear to be limits on what char values can be considered "text" http://www.w3.org/TR/html-markup/syntax.html#text-syntax but, I think such validation goes beyond the scope of your extension. – Jodrell Feb 07 '13 at 12:15