0

I have a 2 Pug files.

The first define config object (base.pug) object like below

const config = { name: 'abc', age: 25}

The other Pug template (main.pug) which includes base.pug and wants to additional property to an object.

script.
  const base = {tech: 'js'}
  const mergedObject = {config, base} // I supposed this should merge 2 object.
  const mergedObjectWithSpreadOp = {...config, tech: 'js'} // again I supposed this should merge 2 object.

Note: pug-runtime used is 2.0.1

None of my approaches worked. How can I achieve this?

I want to merge object from base.pug with main.pug

2
  • Are you trying to render a <script> element client-side with that javascript written out? Or are you wanting to use a merged object server-side in Pug and don't care if it's output client-side? Commented Nov 1, 2023 at 14:40
  • Hello Sean, Thank you for replying. I am trying to "render a <script> element client-side with that javascript written out". Commented Nov 1, 2023 at 17:59

1 Answer 1

0

As you've discovered, writing something in Pug like this—

script.
  const foo = {...config, tech: 'js'}

—just renders that text as-is within a script tag. This is expected behavior for the tag interpolation syntax you're using.

If you want to merge two objects in Pug, and then render the merged object as a string within a script tag, you'll need to do something like this:

script.
  const foo = !{JSON.stringify({...config, tech: 'js'})}

Where:

  • {...config, tech: 'js'} uses the JS spread syntax to create a single new object
  • JSON.stringify(...) converts that object into a string representing it
  • !{...} is the Pug syntax for unescaped string interpolation

That last part is what tells Pug to evaluate that code instead of just rendering as text.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.