I just stumbled upon a weird behavior of Visualforce Components (or apex:variables). Please see the code below and then the end result:

VF Page

    <apex:variable var="foo" value="{!0}" />

    * Before : {!foo}


    * CMP : <c:varTestCmp input="1"></c:varTestCmp>


    * After : {!foo}

VF Component

<apex:component layout="none">
    <apex:attribute name="input" type="Integer"/>
    <apex:variable var="foo" value="{!input + 1}" />



The end result is the following:

enter image description here

It seems that the VF Component and the VF Page are sharing the variables, and the change in VF Component is affecting the variable that is defined outside of it, in VF page.

Now, if I rename the variable inside the component to foo2, I get the expected output:

enter image description here

I haven't used <apex:variable> often, so this caught me by surprise. I was expecting that a variable defined within a component would only be modified within that component.

This could be an issue if someone decides to create a library of reusable components, because, as far as I've seen, even when a component is within another component, and they have a variable with a same name, they will be affecting each other.

Other than naming the variables differently, what other options do we have to isolate them within a containing component?


apex:variable variables always have a global scope. You necessarily need use different variable names in all components and/or pages (e.g. via apex:include). Rarely, it happens that this behavior is desirable if you want to communicate across components, but mostly it is just a hassle. You should avoid using apex:variable for any real work, and instead use wrapper classes and/or attributes, as appropriate, and use Apex Code to manipulate the data.

  • Alright, thank you for the explanation. I'll avoid them in the future.
    – smukov
    Nov 27 '17 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.