Search code examples
expresspugrender

render message in 2 lines in pug file expressjs


I have a expressjs route where i render a product.pug file.

 res.render('product', {
  title: '',
  message: 'Hello.\n'
      + '\n there.',
});

and now want to render these in a new line in a .pug file.Like hello in one line and there will be in another line.But it always shows in a single line

This is what i have done so far in pug/jade file to show the message in two lines

   if message
         .alert.alert-danger(role='alert' style='background-color:#f2dede')
                                                        
                   p(style='color: black')
                                                            
                       message=message

How i can show the message in 2 lines .Can i also pass css through the message in express like font-weight,color. Any help regarding this would be appreciated.


Solution

  • A new line character in HTML text is rendered as a space, provided it is not adjacent to another space-like character.

    To achieve what you want, your Pug view file has to be aware that your data is as you specified it to be. If so, then try:

    if message
      .alert.alert-danger
        p!=message.replace(/\n/g, "<br/>")
    

    The above is dangerous if you are not in control of the message contents. To be safe, add more code:

    if message
      - const lines = message.split("\n")
      .alert.alert-danger
        each line,i in lines
          if i>0
            br
          | #{line}
    

    The last conditional statement is to prevent an extra <br/> if there is no \n in message.