Shaun
Shaun

Reputation: 546

Include Javascript Template String Inside Existing Template String

I have a template string and I need to display different content in it according to the user type.

const postTemplate = (data) => `
    <img alt="Image" src="/images/posts/${ data.post.imageName }" class="video-cover rounded img-fluid" data-action="zoom">
    <div class="d-flex align-items-center">
    <h5 class="mb-4" id="discussion">Discussion</h5>
    <div class="card">
        <div class="js-create-comment collapse px-3 py-2" id="create-comment" data-post-id="${ data.post.id }" aria-expanded="false">
            <div class="media">
                <div class="media-body steps-body">
                    // Include different according to user type
                </div>
            </div>
        </div>
    </div>
`;

I could use a ternary operator but there is a lot of content and I think this would look really messy.

Can anyone suggest a better way I can achieve this? Is it possible to include different template strings from within a ternary operator, inside a template string?

Upvotes: 0

Views: 47

Answers (1)

Adrian Brand
Adrian Brand

Reputation: 21638

I think you have answered your own question with "Is it possible to include different template strings from within a ternary operator, inside a template string?"

const template1 = `<div>template1 markup</div>`;

const template2 = `<div>template2 markup</div>`;

const postTemplate = (data) => `<div>Some markup</div>
  ${ condition ? template1 : template2 }
  <div>More markup</div>`;

All that aside why would you not use a templating engine? Handlebars, Angular, Vue or React? That kind of templating in strings is not very maintainable and turns to spaghetti very quickly.

Upvotes: 1

Related Questions