Home > Net >  Conditional rendering of things in component (ltr to rtl) with minimal duplication?
Conditional rendering of things in component (ltr to rtl) with minimal duplication?

Time:10-05

I’m pretty new to vue so this may be a stupid question. I’m making a multilingual app using vue cli for both english language and arabic language, i’m using the vue-i18n plugin as well. Basically in my components I’ve got multiple things going on in the html template that I need to account for in terms of right to left if the user selects the arabic language. A very simplified example of what I have right now:

<template>
<div>
    <h1>Some text</h1>
    <p>lorem ipsum...</p>
    <button type="button">Button</button>
</div>
</template>

What I need to do is also account for right to left for arabic so I need to align text to the right and put the button on the other side for example, I need to do this for all the code in my other components as well and not just a one off. So is there a better way to do this than using conditional rendering as follows as the code seems very repetitive?

<template>
<div v-if="language=arabic">
    <h1 text-align:right>{{ $t('message') }}</h1>
    <button type="button">Button</button>
    <p>{{ $t('lorem_ipsum') }}</p>
</div>

<div v-else>
    <h1>{{ $t('message') }}</h1>
    <p>{{ $t('lorem_ipsum') }}</p>
    <button type="button">Button</button>
</div>
</template>

Thanks!

CodePudding user response:

What you can do is use css flexbox and then use BEM:

<template>
  <div :class="['has-translation', `has-translation--${this.i18n.locale}`]">
    <h1>{{ $t('message') }}</h1>
    <button type="button">Button</button>
    <p>{{ $t('lorem_ipsum') }}</p>
  </div>
</template>

Then on your CSS you can do:

.has-translations.has-translations--en {
  text-align: left;
}

.has-translations.has-translations--ar {
  text-align: right;
}

If you would like to align (read justify) all lines to the right or left you can:

.has-translations {
  display: flex;
}

.has-translations.has-translations--en {
  justify-content: left;
}

.has-translations.has-translations--ar {
  justify-content: right;
}

I haven't tested the code but this is a general idea I have used in my projects and worked great.

CodePudding user response:

Since this is a lay-out related issue concering the base-structure of your application, my first thought would be to define this at the root of your applcication and not on every component. If your body has a class that define right-to-left, you can style you components accordingly. I don't think your vue-components need to know this information.

  • Related