Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you embed other programming languages into your code?

Tags:

javascript

c#

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.

like image 251
Nathan DeWitt Avatar asked May 20 '09 18:05

Nathan DeWitt


People also ask

How do you combine two programming languages?

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.

Can you use multiple languages in coding?

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 language is embed code?

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.


1 Answers

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.

like image 134
mqp Avatar answered Sep 26 '22 15:09

mqp