You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Odoo 16 JavaScript中继承/重写formatFloat函数?

在Odoo 16 JavaScript中重写formatFloat函数的正确方法

直接通过同名函数重新导出无法覆盖原函数,因为Odoo的模块加载机制不会自动替换第三方模块的导出。需要借助Odoo官方提供的patch工具,结合模块依赖配置来实现全局重写,步骤如下:

1. 配置模块依赖与资源加载

在自定义模块的__manifest__.py中,确保依赖web模块,并声明加载自定义JS文件:

{
    'name': '自定义格式模块',
    'depends': ['web'],
    'assets': {
        'web.assets_backend': [
            'your_module_name/static/src/**/*.js',
        ],
    },
    # 其他manifest配置项...
}

2. 创建重写函数的JS文件

在自定义模块的static/src/views/fields/目录下创建formatters.js(路径建议和原文件结构对齐,便于维护),编写如下代码:

// 导入原函数及所需依赖
import { formatFloat as originalFormatFloat, insertThousandsSep } from '@web/views/fields/formatters';
import { l10n } from '@web/core/l10n/l10n';
import { humanNumber } from '@web/core/utils/numbers';
import { patch } from '@web/core/utils/patch';

// 定义重写后的函数,可按需修改逻辑
export function formatFloat(value, options = {}) {
    if (value === false) {
        return "";
    }
    if (options.humanReadable) {
        return humanNumber(value, options);
    }
    const grouping = options.grouping || l10n.grouping;
    const thousandsSep = "thousandsSep" in options ? options.thousandsSep : l10n.thousandsSep;
    const decimalPoint = "decimalPoint" in options ? options.decimalPoint : l10n.decimalPoint;
    let precision;
    if (options.digits && options.digits[1] !== undefined) {
        precision = options.digits[1];
    } else {
        precision = 3; // 示例:将默认精度从2改为3
    }
    const formatted = (value || 0).toFixed(precision).split(".");
    formatted[0] = insertThousandsSep(formatted[0], thousandsSep, grouping);
    if (options.noTrailingZeros) {
        formatted[1] = formatted[1].replace(/0+$/, "");
    }
    return formatted[1] ? formatted.join(decimalPoint) : formatted[0];
}

// 使用patch覆盖原模块的formatFloat函数
import * as formatters from '@web/views/fields/formatters';
patch(formatters, 'your_module_name/formatters', {
    formatFloat: formatFloat,
});

3. 生效与测试

升级自定义模块,刷新Odoo后台页面后,所有全局调用formatFloat的场景都会自动使用你重写后的函数逻辑。

如果仅需在特定组件中使用自定义逻辑,无需全局覆盖,可直接在对应组件中导入你定义的formatFloat函数使用即可。


内容的提问来源于stack exchange,提问作者Ahmad Zarour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:20:28