In a Sharepoint List: Display an Image (field type “Hyperlink or Picture”)
-
30-01-2021 - |
Question
I have a Sharepoint list that has a column filled with URLs (which point to images stored elsewhere on the Sharepoint site).
The column settings and JSON are shown in the below image:
When I fill in the field for the list items, the URL creates itself as a hyperlink - with the "Enter a url" AND "Enter display text" fields BOTH populated with the link:
If I delete the text out of the "Enter display text" field, the picture displays as expected in the list. Is there a way that I can modify the JSON to remove the need to delete the URL text? I have hundres of items in the list, so doing this deleting for all fields would not be realistic.
Thank you
Here is my JSON
{
"elmType": "img",
"txtContent": "",
"style": {
"width": "100px"
},
"attributes": {
"src": {
"operator": "+",
"operands": [
"@currentField",
"@currentField.desc"
]
}
}
}
Solution
You almost got it. Set src
attribute directly. src
is just URL to an image, so why to use description at all. If you look at the rendered HTML code using Developer dashboard (F12) you will find that the src
of img
tag contains url and description.
Simply use:
{
"elmType": "img",
"style": {
"width": "100px"
},
"attributes": {
"src": "@currentField"
}
}
If you want clickable image use this:
{
"elmType": "a",
"attributes": {
"href": "@currentField",
"target": "_blank"
},
"children": [
{
"elmType": "img",
"style": {
"width": "100px"
},
"attributes": {
"src": "@currentField"
}
}
]
}
I recommend to use $schema
and some intelligent IDE e.g. Visual Studio Code. Using it will give you hints what you can use.
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
"elmType": "div",
"txtContent": "@currentField"
}
Reference: