Variables in locals cannot be used directly in the template rendered by render_ce
Normally, if we render a template in rails with render
method. Like
render template: 'template', locals: { var: 'test'}
In template.html.haml
we can use variable var
without fetch from local_assigns
# template.html.haml
= var # this should work and return string 'test'
Related Rails test https://github.com/rails/rails/blob/main/actionpack/test/controller/new_base/render_template_test.rb#L108
But in gitlab, if we render a template under CE by using render_ce
method in EE environment, we can't use variables in locals directly. We must use local_assings.fetch(:variable)
to get the variable in locals. Here is an example.
# ee/app/views/profiles/notifications/_email_settings.html.haml
- group_managed_account = @user.group_managed_account?
- help_text = group_managed_account ? s_("Your account uses dedicated credentials for the \"%{group_name}\" group and can only be updated through SSO.").html_safe % { group_name: @user.managing_group.name } : nil
= render_ce 'profiles/notifications/email_settings', email_change_disabled: group_managed_account, help_text: help_text, form: form
This haml
file render profiles/notifications/email_settings
template by using render_ce
method, and pass three variables to it(email_change_disabled, help_text and form).
# app/views/profiles/notifications/_email_settings.html.haml
- form = local_assigns.fetch(:form)
.form-group
= form.label :notification_email, class: "label-bold"
= form.select :notification_email, @user.public_verified_emails, { include_blank: _('Use primary email (%{email})') % { email: @user.email }, selected: @user.notification_email }, class: "select2", disabled: local_assigns.fetch(:email_change_disabled, nil)
.help-block
= local_assigns.fetch(:help_text, nil)
.form-group
= form.gitlab_ui_checkbox_component :email_opted_in, _('Receive product marketing emails')
But we can't use email_change_disabled
to get the value, we need use local_assigns.fetch(:email_change_disabled, nil)
to get the value, which is very inconvenient.