Skip to content

Instantly share code, notes, and snippets.

@claytongulick
Last active June 25, 2022 23:32
Show Gist options
  • Save claytongulick/bf05ecebe7a2bbb96b585b74af203eed to your computer and use it in GitHub Desktop.
Save claytongulick/bf05ecebe7a2bbb96b585b74af203eed to your computer and use it in GitHub Desktop.
if statement inside string template literals and lit-html.
//a quick example of how to use actual 'if' statements inside template literals,
//without using ternary operator. Sometimes this is cleaner if you have complex conditionals or nested conditionals.
//data param is passed in via render(template(data), this) - if not using lit-html, could be any function
template = (data) => html`
<div id="job_edit" class="modal">
<div class="modal-content">
${
//we're just going to wrap an anonymous inline function here and then call it with some data
(job => { //job here, is just an example, it could be anything, it's passed in below in (data.job)
if(job)
return html`<h4>Edit Job</h4>`
else
return html`<h4>Create Job</h4>`
})(data.job) //call the anonymous inline with the data we care about
}
</div>
</div>
`;
@claytongulick
Copy link
Author

@franz-josef-kaiser, thanks for the example, but as I mention in the comments:

//a quick example of how to use actual 'if' statements inside template literals,
//without using ternary operator. Sometimes this is cleaner if you have complex conditionals or nested conditionals.

The whole point of this gist is to demonstrate how to use an 'if' statement without the ternary operator. This is especially useful if you have a lot of if/else conditions.

@franz-josef-kaiser
Copy link

@claytongulick I overread that. Anyway, you can still remove the else as you return in the if anyway. Whatever passes the first condition is executed, no matter what. Makes it a bit easier to read and understand when there's no conditional logic wrapped around the command.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment