Using C# for ASP.NET and MOSS development, we often have to embed JavaScript into our C# code. To accomplish this, there seems to be two prevalent schools of thought:
string blah = "asdf";
StringBuilder someJavaScript = new StringBuilder();
someJavaScript.Append("<script language='JavaScript' >");
someJavaScript.Append("function foo()\n");
someJavaScript.Append("{\n");
someJavaScript.Append(" var bar = '{0}';\n", blah);
someJavaScript.Append("}\n");
someJavaScript.Append("</script>");
The other school of thought is something like this:
string blah = "asdf";
string someJavaScript = @"
<script language='JavaScript' >
function foo()
{
var bar = '" + blah + @"';
}
</script>";
Is there a better way than either of these two methods? I like the second personally, as you can see the entire section of JavaScript (or other language block, whether SQL or what have you), and it also aids in copying the code between another editor for that specific language.
Edit:
I should mention that the end goal is having formatted JavaScript in the final web page.
I also changed the example to show interaction with the generated code.
It is possible to combine different languages in one project, you just write two different programmes and let them communicate with each other. And in some cases it even makes sense. Say your project is written in Java or Python for the most part but you have a part that requires a little more computing power.
For native code development, you can (often) link code from several compiled language programs to create executables, libraries and dynamic link libraries or shared objects. For managed code development, the byte-code based Java and . NET virtual machines both support multiple programming languages.
What programming languages are used in embedded systems? Developers use a variety of programming languages in embedded systems. The most used languages include C, C++, Python, MicroPython, and Java.
The second is obviously way, way, clearer. There couldn't really be any reason at all for doing the first.
I would, however, extend it to this:
string someJavaScript = string.Format(@"
<script language='JavaScript' >
function foo()
{
var bar = '{0}';
}
</script>", blah);
If you have several things to stick inside the string, the string.Format method will become rather more readable than inline concatenation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With