How to insert a variable into HTML code

I'm trying to take the contents of the buffer and insert it into HTML code. What is in the buffer is a line of text that will end up being a link to a webpage. I tried the following but it prints the word buffer on the webpage not the contents. Thanks

            buffer = titlesFile.readStringUntil('\n');             
            client.print("<a href=\"/2\"><var>buffer</var></a><br><br>");

This works but is clunky

            buffer = titlesFile.readStringUntil('\n');
            fred = "<a href=\"/1\"><var>";
            alan = "</var></a><br><br>";
            client.print(fred + buffer + alan);

in general it is bad idea to use HTML text in the sketch, better use SPIFFS to store it and if needed you could use processor functions in WebServer libraries to get what you want

Make your html 3 lines, with buffer on its own line. Also see if it is acceptable to use & q u o t ; and do away with the escape character.

@zuelatak

i would avoid to concatenate in the print statement. Just print what is available:

           buffer = titlesFile.readStringUntil('\n');             
           client.print("<a href=\"/2\"><var>");
           client.print(buffer);
           client.print("</var></a><br><br>");

further more, I recommend to use @Juraj StreamLib Library.
See here why:

Isn't there a simple way add a variable into one line of HTML code?

        buffer = titlesFile.readStringUntil('\n');             
        client.print("<a href=\"/2\"><var>buffer</var></a><br><br>");

you can use all technics you know for output on Serial interface.

sprintf, Streaming, StreamLib, ... what ever you like.

IMHO the simple split in 3 lines is what beginners could understand best.

What benefit does that provide over @noiasca's suggestion?

I'm not sure how to use what @noiasca suggested with client.print.
But this worked in the void loop section
client.print("<a href=\"/2\">" + buffer + "</a><br><br>");

and this in the void setup section
buffer = titlesFile.readStringUntil('\n');

I got this from http://randomnerdtutorials.com

You mean you can't copy / paste the provided code?

No, I was referring to using sprintf, Streaming, StreamLib with client.print
Personally I like the one line of code.

Only problem with that is it's use of the String class. Prevailing dogma in these parts is that will fragment you're heap space and cause a catastrophic stack collision. A bit over state perhaps. But if you're using an AVR-based board it's something to consider. If you're on an ARM or ESP with more resources, knock yourself out.

Point taken, I was really trying to figure out how to add a variable into HTML code.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.