Search code examples
javascriptnode.jspug

How should I store pug-formatted content in a database?


I have a javascript app and I'm using pug for templates and diskdb for storing data.

I have some content formatted with pug syntax which could look something in a format like:

p some content here
p some more content here
p: #[span this is the start of the para] #[a(href="http://example.com") a link] #[span and this is the rest of the paragraph]

How could I approach storing this content in my database? So far I've only had to store plain text, but I may need to store some text with links in or bold words for example.


Solution

  • It looks like you have four data points. Here's one way to store the data:

    {
      "opening": "this is the start of the para",
      "url": "http://example.com",
      "link": "a link"
      "closing": "and this is the rest of the paragraph"
    }
    

    This would get sent to the template like this:

    res.render('templateName', { "paragraph": <results from db> });
    

    Which you can then output in pug like this:

    p
      span= paragraph.opening
      | &nbsp;
      span
        a(href= paragraph.url)= paragraph.link
      | &nbsp;
      span= paragraph.closing
    

    (the | outputs raw text after it, and &nbsp; forces the space character)

    Perhaps a better way to store it would be like to insert a token into the paragraph text:

    {
      "text": "this is the start of the para @link and this is the rest of the paragraph",
      "url": "http://example.com",
      "link": "a link"
    }
    

    Then you could output it like this in pug:

    p= paragraph.text.replace(/@link/, '<a href="' + paragraph.url + '">' + paragraph.link + '</a>')