const cocktail = JSON.parse(`
{
"idDrink": "11007",
"strDrink": "Margarita",
"strDrinkAlternate": null,
"strTags": "IBA,ContemporaryClassic",
"strVideo": null,
"strCategory": "Ordinary Drink",
"strIBA": "Contemporary Classics",
"strAlcoholic": "Alcoholic",
"strGlass": "Cocktail glass",
"strInstructions": "Rub the rim of the glass with the lime slice to make the salt stick to it. Take care to moisten only the outer rim and sprinkle the salt on it. The salt should present to the lips of the imbiber and never mix into the cocktail. Shake the other ingredients with ice, then carefully pour into the glass.",
"strInstructionsES": null,
"strInstructionsDE": "Reiben Sie den Rand des Glases mit der Limettenscheibe, damit das Salz daran haftet. Achten Sie darauf, dass nur der u00e4uu00dfere Rand angefeuchtet wird und streuen Sie das Salz darauf. Das Salz sollte sich auf den Lippen des Genieu00dfers befinden und niemals in den Cocktail einmischen. Die anderen Zutaten mit Eis schu00fctteln und vorsichtig in das Glas geben.",
"strInstructionsFR": null,
"strInstructionsIT": "Strofina il bordo del bicchiere con la fetta di lime per far aderire il sale.Avere cura di inumidire solo il bordo esterno e cospargere di sale. Il sale dovrebbe presentarsi alle labbra del bevitore e non mescolarsi mai al cocktail.Shakerare gli altri ingredienti con ghiaccio, quindi versarli delicatamente nel bicchiere.",
"strInstructionsZH-HANS": null,
"strInstructionsZH-HANT": null,
"strDrinkThumb": "<https://www.thecocktaildb.com/images/media/drink/5noda61589575158.jpg>",
"strIngredient1": "Tequila",
"strIngredient2": "Triple sec",
"strIngredient3": "Lime juice",
"strIngredient4": "Salt",
"strIngredient5": null,
"strIngredient6": null,
"strIngredient7": null,
"strIngredient8": null,
"strIngredient9": null,
"strIngredient10": null,
"strIngredient11": null,
"strIngredient12": null,
"strIngredient13": null,
"strIngredient14": null,
"strIngredient15": null,
"strMeasure1": "1 1/2 oz ",
"strMeasure2": "1/2 oz ",
"strMeasure3": "1 oz ",
"strMeasure4": null,
"strMeasure5": null,
"strMeasure6": null,
"strMeasure7": null,
"strMeasure8": null,
"strMeasure9": null,
"strMeasure10": null,
"strMeasure11": null,
"strMeasure12": null,
"strMeasure13": null,
"strMeasure14": null,
"strMeasure15": null,
"strImageSource": "<https://commons.wikimedia.org/wiki/File:Klassiche_Margarita.jpg>",
"strImageAttribution": "Cocktailmarler",
"strCreativeCommonsConfirmed": "Yes",
"dateModified": "2015-08-18 14:42:59"
}
`);
Шаблонизация строками – это когда мы просто формируем HTML-код с помощью шаблонных строк, или склеивая строки через +
, после чего добавляем этот код в интерфейс через innerHTML
:
element.innerHTML = `
<article class="cocktail">
<header class="cocktail__header">
<a href="${cocktail.strImageSource}">
<div class="cocktail__image" style="background-image: url('${cocktail.strDrinkThumb}');"></div>
</a>
<h2 class="cocktail__title">
<span class="cocktail__title-text">
${cocktail.strDrink}
</span>
<i class="fa-solid ${cocktail.strAlcoholic === 'Alcoholic' ? 'fa-wine-glass' : 'fa-0'}"></i>
</h2>
</header>
<div class="cocktail__main">
<p class="cocktail__description">
${cocktail.strInstructions}
</p>
</div>
</article>
`;
Плюсы:
Минусы:
<aside>
💡 XSS-уязвимость – это возможность злоумышленнику выполнить свой код на вашем сервисе. В шаблоне выше, если данные будут получены от внешних источников (от пользователя или от стороннего API) то их можно сформировать так, что будет выполнен JavaScript-код. Например, подмешать в этим данные соответствующие html-атрибуты, вроде onmouseover
, и т.п.
</aside>
Тут мы имеем ввиду шаблонизацию за счет стандарных методов для создания объектов узлов и добавления их в DOM-дерево, таких как document.createElement
, node.appendChild
и т.п.
Функция с шаблоном, аналогичным предыдущему:
function browserCocktailTemplate(cocktail) {
const cocktailElement = document.createElement('article');
cocktailElement.classList.add('cocktail');
const cocktailHeader = document.createElement('header');
cocktailHeader.classList.add('cocktail__header');
cocktailElement.appendChild(cocktailHeader);
const cocktailLink = document.createElement('a');
cocktailLink.href = cocktail.strImageSource;
cocktailHeader.appendChild(cocktailLink);
const cocktailImage = document.createElement('div');
cocktailImage.classList.add('cocktail__image');
cocktailImage.style.backgroundImage = `url('${cocktail.strDrinkThumb}')`;
cocktailLink.appendChild(cocktailImage);
const cocktailTitle = document.createElement('h2');
cocktailTitle.classList.add('cocktail__title');
cocktailHeader.appendChild(cocktailTitle);
const cocktailTitleText = document.createElement('span');
cocktailTitleText.classList.add('cocktail__title-text');
cocktailTitleText.textContent = cocktail.strDrink;
cocktailTitle.appendChild(cocktailTitleText);
const cocktailTitleIcon = document.createElement('i');
cocktailTitleIcon.classList.add('fa-solid', cocktail.strAlcoholic === 'Alcoholic' ? 'fa-wine-glass' : 'fa-0');
cocktailTitle.appendChild(cocktailTitleIcon);
const cocktailMain = document.createElement('div');
cocktailMain.classList.add('cocktail__main');
cocktailElement.appendChild(cocktailMain);
const cocktailDescription = document.createElement('p');
cocktailDescription.classList.add('cocktail__description');
cocktailDescription.textContent = cocktail.strInstructions;
cocktailMain.appendChild(cocktailDescription);
return cocktailElement;
}
Плюсы: