Embedding a string within an image source attribute in VueJS

My goal is to extract the name of a job department as data for a Vue component, convert it to lowercase, and then use it to dynamically render the correct image based on the department's name. The images are named after the departments.

The current code snippet looks like this:

<ul class="jobs-container">
  <li
      v-for="job in filteredJobs"
      :key="job.absolute_url"
      class="u-margin-bottom-small">
    <a :href="job.absolute_url" target="_blank">
      <img src="/wp-content/themes/theme/dist/images/icons/careers/engineering.svg" alt="Engineering" />
      <div>
        <h3 v-html="job.departments[0].name" />
        <span class="position" v-html="job.title" />
      </div>
      <span class="location" v-html="job.offices[0].location" />
    </a>
  </li>
</ul>

I am trying to achieve something like this:

<ul class="jobs-container">
  <li
      v-for="job in filteredJobs"
      :key="job.absolute_url"
      class="u-margin-bottom-small">
    <a :href="job.absolute_url" target="_blank">

      // insert name of job department
      <img src="/wp-content/themes/theme/dist/images/icons/careers/{{ job.departments[0].name.toLowerCase() }}.svg" alt="Engineering" />

      <div>
        <h3 v-html="job.departments[0].name" />
        <span class="position" v-html="job.title" />
      </div>
      <span class="location" v-html="job.offices[0].location" />
    </a>
  </li>
</ul>

When attempting this approach, I encounter an error message:

ERROR Failed to compile with 1 errors 4:02:34 PM

error in ./wp-content/themes/theme/assets/js/Careers. vue?vue&type=template&id=bf690b58&

Module Error (from ./node_modules/vue-loader/lib/loader s/templateLoader.js): (Emitted value instead of an instance of Error)

Errors compiling template:

src="/wp-content/themes/theme/dist/images/icons/caree rs/{{ job.departments[0].name }}.svg": Interpolation inside attributes is no longer supported. Use v-bind or the colon shorthand instead. For example, replace <div id="{{ val }}"> with <div :id="val">.

30 | class="u-margin-bottom-small"> 31 | 32 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 33 | 34 |

To resolve this, I've tried using :src for the image source:

<img :src="/wp-content/themes/theme/dist/images/icons/careers/{{ job.departments[0].name.toLowerCase() }}.svg" alt="Engineering" />

However, this leads to another error:

ERROR Failed to compile with 1 errors 4:06:01 PM

error in ./wp-content/themes/theme/assets/js/Careers. vue?vue&type=template&id=16c0d4b0&

Module Error (from ./node_modules/vue-loader/lib/loader s/templateLoader.js): (Emitted value instead of an instance of Error)

Errors compiling template:

invalid expression: Invalid regular expression flags in

/wp-content/themes/theme/dist/images/icons/careers/{{ job.departments[0].name }}.svg

Raw expression: :src="/wp-content/themes/theme/dist/images/icons/careers/{{ job.departments[0].name }}.svg"

30 | class="u-margin-bottom-small"> 31 | 32 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 33 | 34 |

@ ./wp-content/themes/theme/assets/js/Careers.vue?vue&type=template&id=16c0d4b0& 1:0-223 1:0-223 @ ./wp-content/themes/theme/assets/js/Careers.vue @ ./wp-content/themes/theme/assets/js/careers.js @ ./wp-content/themes/theme/assets/js/main.js @ multi ./wp-content/themes/theme/assets/js/main.js ./wp-content/themes/theme/assets/sass/base.scss

In Vue context, can someone guide me on how to properly use

job.departments[0].name.toLowerCase()
to incorporate it into the final part of
<img src="/wp-content/themes/theme/dist/images/icons/careers/(INJECT IT HERE).svg" alt="Engineering" />

Answer №1

Implement template literals in your code:

  <img :src="`/path/${product}.jpg`" alt="Product Image" />

Answer №2

Just a reminder, when using the binding syntax, remember to enclose your URL in single quotes so it is interpreted as a string:

<img :src="'/wp-content/themes/theme/dist/images/icons/careers/' + job.departments[0].name.toLowerCase() + '.svg" alt="Engineering'" />

An alternative approach is to store the entire URL in a variable:

let dynamicURL = '/wp-content/themes/theme/dist/images/icons/careers/' + job.departments[0].name.toLowerCase() + '.svg';

<img :src="dynamicURL" />

Answer №3

To avoid issues with Vue interpreting literal text as JavaScript, it is important to escape the text using ' when using the colon shorthand. More information on this topic can be found in this question. The error message "Invalid regular expression flags" occurs because JavaScript interprets any content within / as a regular expression. For example:

:src="'/wp-content/themes/theme/dist/images/icons/careers/' + job.departments[0].name + '.svg'"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to convert a jQuery function to plain JavaScript code?

Struggling with my homework, I must apologize for any mistakes in my English. My task involves creating a chat using node.js and I found some code snippets on a website "" which I used successfully. The issue now is that the chat relies on old jQuery libr ...

What is the best way to restrict the creation of objects in a JavaScript list?

Experiencing a fun challenge with HTML coding! Take a look at my ordered list in HTML: <ol id="myList"> <li>Tea</li> <li>Milk</li> <li>Water</li> </ol> <button onclick="myFunction()">Try it</ ...

What is the best method for storing decimal values as floating-point numbers?

I am currently developing a Vue project where I need to store variables in decimal numbers using point notation. For example, if I input 23,5 it should be saved as 23.5. function school (ind){ this['School Name'] = "", this['Subj ...

TemplateUrl malfunctioning

While experimenting with basic Angular code, I encountered an issue where everything was functioning correctly when using template, but not when switching to templateUrl. I did not provide the previous code as it was working fine except for this specific c ...

I have a specific resolution in mind where I want to run jQuery code during window scrolling

I have a jQuery code that I want to run only when the resolution is greater than 950px. If not, I risk losing the responsive logo. My goal is to create a navigation bar similar to the one on the Lenovo homepage. $(document).ready(function(){ //left ...

Adding jQuery content to a div that is being created dynamically

Currently implementing a save/load feature using JSON for a diagram that utilizes jsPlumb. While the save functionality is working perfectly, the load functionality is encountering difficulties in replicating the full initial saved state. The issue arises ...

Fixing the Responsive Menu Issues

In order to achieve the desired effect of making the text from menu and logo disappear when minimizing the menu, you can use the following approach: Create a function called `smallNav()` to handle the resizing of the sidebar container: function sm ...

Press a single button to toggle between displaying and hiding the table

$(document).ready(function() { $("#t1").hide(); // hide table by default $('#sp1').on('click', function() { $("#t1").show(); }); $('#close').on('click', function() { $("#t1").hide(); }); }); <li ...

Unable to use the same hexadecimal HTML entity in the value props of a React JSX component

Can someone explain why this code snippet displays dots as password and the other displays plain hexadecimal codes? <Field label="Password" value="&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;" type="password" /> While this one disp ...

Placing a material UI Radio button within a row cell on a table

Here is the current design snapshot: https://i.sstatic.net/yRFWD.png I am working with Material UI's radio button component and I want to ensure that each row in the table can be selected only once. Although I am able to select a single row using the ...

Ways to expand the play and pause buttons and adjust the height of an HTML audio player

It's clear that the PLAY/PAUSE icons are smaller than intended, and the entire player is thinner than desired, making it difficult for some viewers to see. How can I enlarge the entire player? I have read that we do not have access to individual contr ...

Utilize node.js on your local machine and leverage gulp to monitor any modifications

I recently copied a repository from https://github.com/willianjusten/bootstrap-boilerplate and followed these steps. git clone git://github.com/willianjusten/bootstrap-boilerplate.git new_project cd bootstrap-boilerplate npm install gulp The gulp comman ...

How to showcase base64 encoded images in pug (jade) with node.js

Can anyone help with decoding this mysterious data and displaying the image? I'm using pug as my template engine. Below is the questionable data that needs to be shown as an image: /9j/4AAQSkZJRgABAQEAYABgAAD/4QBaRXhpZgAATU0AKgAAAAgABQ ...and so f ...

Mesh does not display texture in three.js

I've been attempting to add a texture to my sphere mesh using the code snippet below: var loader = new THREE.TextureLoader(); var balltex = loader.load("pic1.jpg"); var ballmat = new THREE.MeshBasicMaterial({ map: balltex }); var ballgeo = new THREE ...

Discover additional information using just the ID

I am developing a simple app and facing an issue with extracting information from furnitures.js: export default [ { id: 1, name: 'Sofa Sydney', dim1: '2.25m', dim2: '1.45m x 1.95m'}, { id: 2, name: 'Sofa Alex&apos ...

What is the process for the event loop moving into the poll phase?

There is a scenario outlined in the event loop explanation on the Node.js official website. When setTimeout is triggered, and the callback queue for the timer phase isn't empty, why does the event loop move on to the poll phase? The site mentions that ...

Setting up the JSON reply

When creating a schema using Joi and expecting a JSON response that matches the schema upon POSTing, an issue arises. The dilemma is having to include a parent element (in this case "data:") in the JSON response, although ideally the schema's attribut ...

"Adding an Image to Another Image in HTML or JavaScript: A Step-by-Step

Hello there! I'm currently working on creating a status bar where I can add an image after another image. Let me explain my idea clearly. So, I have two images in GIF format: one is white and 10x10px, and the other one is black and also 10x10px. On ...

In VueJS 3, the data within the app.component instance will lack reactivity if it is declared within the data() or setup() functions

When it comes to declaring new reactive variables inside a component, I faced an interesting issue. It seems that setting the component globally, outside the app.component instance, and then returning it to either the data() or setup() function works perfe ...

Swapping out 'useResult' in graphql for Vue and Apollo: A step-by-step guide

I need to replace the useResult function that is fetching data from GraphQL with a computed function. const locationOptions = useResult( result, [], ({ getLocations }): Option[] => formatOptions(getLocations) ) Instead, I want ...