Search code examples
javascriptexpresspug

Inserting image in table cell with PUG


I'm making a call to an API and i'm using PUG to display the results. One of the properties is an image link and I want to display the image in the last column (maybe set a responsive height and weight so a large image doesn't take the whole page).

I'm passing an array of objects and the image link is found here: item.result.image.contentUrl

html

  head
    title= Results
    link(rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous")
    body
      table(class="table table-striped")
        thead(class="thead-dark")
          tr
            th(scope="col") Result for #{searchTerm}
            th(scope="col") Description
            th(scope="col") Image
        tbody
            each item in searchData
                tr
                    td(scope="row")= item.result.name
                    td(scope="row")= item.result.description
                    if !item.result.image
                      td(scope="row") Image not found
                    else
                      td(scope="row") img(src= item.result.image.contentUrl)

The last row as you can see is wrong, but I haven't been able to find any resources on this. Any suggestions?


Solution

  • You need to put the img on a new line indented under the td in order for it to be its own tag:

    td(scope="row")
      img(src= item.result.image.contentUrl)
    

    While we're at it, I'd recommend that you flip your conditional around to be easier to read:

    if item.result.image
      td(scope="row")
        img(src= item.result.image.contentUrl)
    else
      td(scope="row") Image not found
    

    or even better:

    td(scope="row")
      if item.result.image
        img(src= item.result.image.contentUrl)
      else
        div Image not found