Search code examples
javascriptpug

How do I escape a space in Jade(pug) template just in template file?


I did some search but couldn't find any people discussing this.

Here is my issue.

I have a variable passed in Jade Compiler and it contains space in it.

For example:

<a href="#{option.content}">test link</a>

What if there are spaces in the option.content part. Do I have to escape it before it's passed in the HTML page?


Solution

  • This is really JavaScript and not pug, but you still see this a lot in pug when you're parsing JSON inputs.

    The first variable name can't have spaces in it by JavaScript object standards, but properties of a JavaScript object can definitely have spaces in them. Let's take this (really poorly designed) object as an example:

    var myObject = {
      "object type": "person",
      "person name": {
        "first name": "Lebron",
        "last name": "James",
        "initials": "LJ"
      }
    };
    

    You can access individual fields using square brackets and the property name in quotes, and fields that don't have spaces can still use periods:

    myObject['object type']                 // returns "person"
    myObject['person name']['first name']   // returns "Lebron"
    
    myObject['person name'].initials        // returns "LJ"
    myObject['person name']['initials']     // returns "LJ"