bluewings/pug-as-jsx-loader

How to properly use variable with inline syntax

Closed this issue · 3 comments

I can't figure out the proper syntax to render variables from my react props into the pug template syntax. I'm not using external pug files, but rather the inline pug syntax within my react .js files.

Example: my Home.js file looks something like this

import React, {component} from 'react'
import {Card, CardBody, CardTitle} from 'reactstrap'

export default class Home extends Component {
   constructor(props) {
     super(props)
     this.data = props.data
   }

    render() {
       return pug`
          Card
               CardBody
                   CardTitle '{props.data.title}'
       `
    }

}

And that works just fine, but the problem is that quotes appear around my title. So if
props.data.title = "Hello world"

then it comes out as 'Hello world' on the page.

I tried different combinations of syntax like ${props.data.title} and CardTitle= #{props.data.title}

but all of them end up with an error either by the pug-lexer or the pug-as-jsx-loader

AAAhhh, I figured it out literally minutes after posting this!

the proper syntax is:

CardTitle= '{props.data..title}'

and if you want to have text beforehand like Title: '{props.data..title}'
you can do:

- var title = '{props.data.title}'
CardTitle posted at #{title}

I'm going to leave this issue open for now, because maybe there's an easier syntax that I'm unaware of. This syntax works, but having to declare a variable just to use it as part of a string seems like a hack. Is there a better way to do this?

@nikita-skobov
You do not need to enclose it in single quotation marks.
If you use it as an attribute, you need to use quotation marks, but if you use it to put variable as a text, just use { expression }

import React, { component } from 'react';
import { Card, CardBody, CardTitle } from 'reactstrap';

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.data = props.data;
  }

  render() {
    const { props } = this;
    return pug`
      Card
        CardBody
          CardTitle {props.data.title}
    `;
  }
}

@bluewings

That's perfect thank you!