1

I have used the backticks syntax in order to generate some Java code with Javascript:

${body ? `con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(${JSON.stringify(body)});
wr.flush();
wr.close();` : ``}

int responseCode = con.getResponseCode();

However, when body is null, the generated code contains 3-4 empty lines and then the "int responseCode .." line. I have tried extracting the part where body is true into a separate constant or moving the `` as first in the statement and none of them works. Any suggestions?

Thanks in advance!

  • 2
    Why do you have `${` before `body`? – Heretic Monkey Feb 21 '17 at 18:41
  • The `${....}` syntax works only inside backticks, so its curious why the first line has this syntax outside of backticks. More curiously, you aren't getting a "Syntax error: Unexpected token {" error? –  Feb 21 '17 at 18:44
  • Sorry. It's within backticks, it's something like: ``..... ${body ? `con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(${JSON.stringify(body)}); wr.flush(); wr.close();` : ``} int responseCode = con.getResponseCode(); .....`` – Ivan Panchev Feb 22 '17 at 13:18

1 Answers1

0

Maybe if you check correctly the body's var, e.g:

typeof body == "undefined" ? `con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(${JSON.stringify(body)});
wr.flush();
wr.close();` : ``

Will return the string below:

"con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(${JSON.stringify(body)});
wr.flush();
wr.close();"

Not use just body ? "string" : "", do some operation with the body's var. (e.g body == "" or typeof body == "undefined")

Herlon Aguiar
  • 684
  • 2
  • 9
  • 18