Reputation: 23
I'm making a site for my game server, and I'm trying to display user information using the Steam API.
$.getJSON('/steamapi', function(data) {
document.getElementById("staff-inner").innerHTML = `${data.response.players.map(function(player) {
return `
<div class="player player-${player.steamid}">
<div class="name">${player.personaname}</div>
<div class="avatar"><img src="${player.avatarfull}"></div>
<div class="role"></div>
</div>
`;
}).join('')}`;
});
The above code is working fine. But, what I'm trying to do (and I assume this is the best way) is create an if statement that says if ${player.steamid} is my Steam ID, it prints 'Owner' in .role, and prints 'Moderator' if it's anything else. Seems like it would be simple enough, but everything I try leaves me with a blank page. I have no idea how or where I would write it in this context.
Upvotes: 2
Views: 517
Reputation: 19
I don't get enough time to test this with steamAPI but I think it'll work :
const appDiv = document.getElementById('app');
const my_steam_id = 'Rex4748';
const players = [{
steamid: 'Rex4748',
avatarfull: 'https://fakeimg.pl/50/',
personaname: 'Joe Perez'
},{
steamid: 'notYou',
avatarfull: 'https://fakeimg.pl/50/',
personaname: 'NewGuy'
}]
function getPlayers(){
let info_collected = [];
players.map((player)=> {
console.log(player.steamid);
info_collected.push(`
<div class="player player-${player.steamid}">
<div class="name">
${player.personaname}
</div>
<div class="avatar">
<img src="${player.avatarfull}">
</div>
<div class="role">
${player.steamid == my_steam_id ?
'Owner' :
'Moderator'}
</div>
</div>
<hr>
`);
})
return info_collected.join('');
}
appDiv.innerHTML = getPlayers();
Pen : https://stackblitz.com/edit/using-json-objects-in-if-statements
Upvotes: 0
Reputation: 103
Either you can declare a variable before your return statement and call the reference
let role = player.steamid == '111' ? 'Owner' : 'Moderator'
and then
<div class="role">${role}</div>
Upvotes: 0
Reputation: 198324
Inside a template string, only expressions are allowed, not statements. if
is a statement; but there's the conditional operator (?:
) which has almost the same semantics.
`...
<div class="role">${player.steamid == 'Rex4748' ? 'Owner' : 'Moderator'}</div>
...`
Upvotes: 3