0

I have a question about referencing image in HTML. I have a single snippet of HTML code as below, where I need to reference an image in a folder called static. The image has an extension of SVG but it's name is dynamically created. If there a way for HTML to refer to this image by only referring to the file extension? The code below using a wild card doesn't work.

<p>
<img src="/static/*.svg" width="1000">
</p>

Additionally, can we add a logic in HTML such that if there is no SVG file in static folder, we don't render it; if there is one, then render it.

Thank you.

Chenyang
  • 161
  • 1
  • 11

2 Answers2

2

I don't think it's possible to do what you're asking with just HTML. However you can easily do this by adding an id to the tag and applying the attribute based on your condition. There are plenty of examples on the web on how to do this including one already answered here: Javascript set img src

Alejandro
  • 623
  • 1
  • 9
  • 22
  • This would be part of the solution, along with a way to get a list of files in a directory. Some servers do provide that info, others don't, depending on what features are available and enabled. – Garrett Motzner Feb 09 '21 at 17:21
1

This is possible with a server that is designed for this purpose. There is not a feature of just html that will do this, however. If you don't control the server on the backend, you probably can't get this to work, as it most likely will require custom backend code.

On the backend, you make a simple static html server that will match file patterns, and determine and serve the best match. You can do this any number of ways, and if you look up "how to make a static http server" for your favorite backend language, you likely will find an example to get you started, like these:

You would then have to modify whatever base example you chose with your custom pattern matching code. Your server could be designed to do whatever you wanted with the request you send it, including the scenario you described.

This works because an img tag like the one in your example causes the browser to make a GET http request to your server, passing on the url in the src attribute. So, if you control that server, you can have it respond in any way you want, including treating specific characters like * specially.

Garrett Motzner
  • 3,021
  • 1
  • 13
  • 30