1

I'm trying to store HTML in a Javascript Variable so that it's easy to read and edit in the future.

I've done this:

var form = [
    "<fieldset>",
    "  <label></label>",
    "</fieldset>" ].join("\n");

Only thing is I want it to be easier than that to edit in the future, possibly store it in a variable in PHP (if that's any easier) and then encode it or something.

There is going to be a whole lot more HTML then that

Talon
  • 4,937
  • 10
  • 43
  • 57

4 Answers4

1

In PHP variable:

$form =<<<FORM
<fieldset>
    <label></label>
</fieldset>
FORM;

http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Anthony
  • 71
  • 4
0

If the PHP option you mentioned is the way you want to go, one option (that's very readable and easily editable) would be something like:

$out = '<div>';
    $out .= '<p>Hello, World</p>';
$out .= '</div>;

The largest advantage (I think) is that this allows you to indent freely for readability. Obviously a very simple example, but hopefully the point gets across.

orourkek
  • 2,091
  • 15
  • 22
0

You can write multi-line strings by adding backslashes to each line:

Creating multiline strings in JavaScript

Community
  • 1
  • 1
garious
  • 91
  • 3
0

I would use jQuery templates.

http://blog.reybango.com/2010/07/09/not-using-jquery-javascript-templates-youre-really-missing-out/

Your example:

<script id="myTemplate" type="text/html">
    <fieldset><label></label></fieldset>
</script>

Additionally, the templates allow you to add in variables, for example:

<script id="myTemplate" type="text/html">
    <fieldset><label class="${labelclass}">${label}</label></fieldset>
</script>    

You pass in the information as an array

var templateData = [
    { labelclass: "fruit", label: "orange" },
    { labelclass: "vegetable", label: "cucumber" },
    { labelclass: "animal", label: "dog" }
];

Then you can append to where you want

$("#myTemplate").tmpl(templateData ).appendTo( "form" );

You don't have to use the variables, but it's much cleaner than trying to construct it manually.

Kay
  • 70
  • 2
  • 8